问题:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/?tab=Description
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).
分析:选择买入卖出股票的最大收益,但是第二次买入必须在第一次卖出的时间节点之后,,此时存在一个局部最优,即 2 4 5 3 6 8,此时8-2一定小于5-2+8-3,,因此就有取数组每次递增的收益即为局部最优,然后所有的局部最优加起来就是全局最优。
参考C++代码:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int p=0;
for(int i=1;i<prices.size();i++){
if(prices[i]>prices[i-1])
p+=prices[i]-prices[i-1];
}
return p;
}
};