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).
思路: 在遇到高于最高点和低于最高点的时候都要进行判定。当高于最高点,说明可以刷新最高点,继续前进,当低于最高点,应该立刻抛掉,然后刷新最低点和最高点。
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() <= 1) return 0;
int minP = prices[0];
int maxP = prices[0];
int maxD = 0;
for (int i = 1; i < prices.size(); i++){
if (prices[i]>maxP){
maxP = prices[i];
}
if (prices[i] < maxP){
maxD += (maxP - minP);
maxP = prices[i];
minP = prices[i];
}
}
if (maxP>minP)
maxD += (maxP - minP);
return maxD;
}
};