LeetCode 122 Best Time to Buy and Sell Stock II
Say you have an array for which the ith element is the price of a given stock on day i.
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).
DiffcultyMedium
Similar Problems
LeetCode 122 Best Time to Buy and Sell Stock II
[LeetCode 123] Best Time to Buy and Sell Stock III
[LeetCode 124] Best Time to Buy and Sell Stock IV
[LeetCode 309] Best Time to Buy and Sell Stock With Cooldown
Analysis
思路一: 这道题跟 Best Time to Buy and Sell Stock 类似,求最大利润。 区别是这里可以交易无限多次(当然我们知道交易不会超过n-1次,也就是每天都进行先卖然后买)。 既然交易次数没有限定,可以看出我们只要对于每次两天差价大于0的都进行交易,就可以得到最大利润。 因此算法其实就是累加所有大于0的差价既可以了,非常简单。 最大收益可以由所有上升序列差价叠加中获得, greedy方法 即,只要prices[i] - prices[i-1] > 0,我们就在第i-1天买入,第i天抛出。这样可以包括所有可能赚取利润的区间。 如此只需要一次扫描就可以了,时间复杂度是O(n),空间上只需要O(1)存一个累加结果即可。代码如下:
思路二:找到所有价格的递增区间,每个区间内以对低价买入最高价卖出
Solutions
解法一
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sum = 0;
for(int i = 1; i < (int)prices.size(); ++i){
if(prices[i] > prices[i - 1])
sum += prices[i] - prices[i - 1];
}
return sum;
}
};
解法二
class Solution {
public:
int maxProfit(vector<int> &prices) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int n = prices.size();
if(n <= 1) return 0;
int i = 0;
int res = 0;
while(i < n - 1){
int buy, sell;
//递减区间
while(i + 1 < n && prices[i+1] < prices[i]) i++;
buy = i++;
//递增区间
while(i < n && prices[i] >= prices[i-1])i++;
sell = i-1;
res += prices[sell] - prices[buy];
}
return res;
}
};