问题:
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).
分析:如果股票的价格是一张折线图的话,由于我们可以无限次买卖股票,我们只需要在每一个波谷的地方买入,然后在下一个波峰的地方卖出即可。而这又等价于:只要后面一天的价格比前面一天高,我就在前面一天买,后面一天卖。这样我就赚取了所有可能的利润。
代码:(O(n))
class Solution {
public:
int maxProfit(vector<int> &prices) {
if (prices.size() <= 1) return 0;
int buy_day = 0;
int result = 0;
for (int i = 1; i < prices.size(); i ++) {
if (prices[i - 1] < prices[i])
result += (prices[i] - prices[i - 1]);
}
return result;
}
};