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 length=prices.size();
int cost=0;
for(int i=length-2;i>=0;i--){
if(prices[i]<prices[i+1]){
cost+=prices[i+1]-prices[i];
}
}
return cost;
}
};
贪心算法的最简单例子。
从末至始开始计算遵循以下规则:
有商品售价序列S(1~n)按日期升序排列。
第k日的商品售价为A(k)
假设第k+1日~第n日的最大利润即子问题S(k+1~n)的最优解已经求出。
若第k日的售价比k+1日便宜,则子问题S(k~n)的最优解为S(k+1~n)加上k和k+1日的商品差价。
否则最优解仍为S(k+1~n)。
所以只需反向按照以上规则累加即可
时间复杂度O(n),空间复杂度O(1)