122. Best Time to Buy and Sell Stock II
来源:互联网 发布:华讯网络北京怎么样 编辑:程序博客网 时间:2024/05/20 13:39
Say you have an array for which the ith element is the price of a given stock on dayi.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Subscribe to see which companies asked this question
分析:
神鬼难测的算法。
假设a<b<c<d<e;
则应该返回ans=e-a=(e-d)+(d-c)+(c-b)+(b-a);
假设a<b>c<d<e;
则应该返回ans=e-c+b-a=(e-d)+(d-c)+0+(b-a);
代码如下:
class Solution {public: int maxProfit(vector<int>& prices) { int ret=0; for(int i=1;i<prices.size();++i) ret+=max(prices[i]-prices[i-1],0); return ret; }};
0 0
- 122. Best Time to Buy and Sell Stock II
- LeetCode 122. Best Time to Buy and Sell Stock II
- 122.Best Time to Buy and Sell Stock II
- [Leetcode] 122. Best Time to Buy and Sell Stock II
- [leetcode] 122.Best Time to Buy and Sell Stock II
- 【leetcode】122.Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II
- 【LeetCode】122.Best Time to Buy and Sell Stock II
- [leetcode] 122. Best Time to Buy and Sell Stock II
- LeetCode #122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II LeetCode
- 122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II
- [LeetCode]122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II
- Leetcode 122. Best Time to Buy and Sell Stock II
- leetcode 122. Best Time to Buy and Sell Stock II
- 【7】机器学习之一脉相承:聚类纵论
- VPN篇(5.2)-06. IPsec VPN 星状拓扑 ❀ 飞塔 (Fortinet) 防火墙
- MiniDebugger需要改进的点
- Codeforces Round #356 (Div. 2) A - Bear and Five Cards
- CSS clip:rect用法
- 122. Best Time to Buy and Sell Stock II
- Java中选择排序的代码实现
- Android:Dagger2学习之由浅入深
- 使用lame转换mp3时,出现libmp3lame missing required architecture x86_64
- oj数据结构代码(前半期+后半期)
- Codeforces Round #356 (Div. 2) B Bear and Finding Criminals
- Ikki's Story IV - Panda's Trick_poj3207_2-sat
- orcle数据库system口令忘记怎么办
- zynq ALSA