贪心策略,每次在山谷买入,在山顶卖出,如图所示。
变形等价于如下“爬山”算法
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size(), profit = 0;
for(int i=0;i<n-1;i++){
if(prices[i+1]>prices[i]) profit+=prices[i+1]-prices[i];
}
return profit;
}
};