https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
给定一个数组,其中数组的第 i 个元素表示第 i 天的股票价格,你可以选择在其中一天买股票,然后再后面的某一天卖掉股票,求最大收益。(股票必须要先买才能卖)这里可以购买多次,也可以卖出多次
-------------------
Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
-----------------
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
---------------------
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
分析:
与 https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 类似,解答见https://www.jianshu.com/p/cdb6881094f0,区别在于这里可以买卖多次
法一
我们可以依次找到局部最小值,然后再在局部最小值后面找到局部最大值,在这两个地方买进和卖出;然后再依次往后找:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int buy = 0, sell = 0;
int i = 0, len = prices.size()-1;
int profit = 0;
while(i < len)
{
while(i < len && prices[i+1] <= prices[i]) // find the local minimum
++i;
buy = prices[i]; // buy at the local minimum
while(i < len && prices[i+1] >= prices[i]) // find the local maximum
++i;
sell = prices[i]; // sell at the local maximum
profit += (sell-buy);
}
return profit;
}
};
结果:
Runtime: 4 ms
Memory Usage: 7.4 MB
方法2
从 121. Best Time to Buy and Sell Stock,我们可以知道,
nums[j] - nums[i] = nums[j] - num[j-1] + nums[j-2] - nums[j-3] + .... + nums[i+1] - nums[i]
方法一也是找到一个局部递增子数组,因此可以直接判断 如果 nums[i+1] > nums[i]
,就可以直接买进和卖出
class Solution {
public:
int maxProfit(vector<int>& prices) {
int profit = 0;
for(int i = 1; i<prices.size(); ++i)
{
if(prices[i] > prices[i-1])
{
profit += (prices[i]-prices[i-1]);
}
}
return profit;
}
};
结果
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Best Time to Buy and Sell Stock II.
Memory Usage: 7.4 MB, less than 100.00% of C++ online submissions for Best Time to Buy and Sell Stock II.
网友评论