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).
刚做了 Best Time to Buy and Sell Stock I问题,Best Time to Buy and Sell Stock II要求可以无限次买卖股票, 条件是一天内只有在卖出股票后才能买股票。
这题属于贪心算法,我们只要根据局部最优原则就能得到全局最优(即利润最大)。因为我们已经知道了若干天股票的走势,所以当今天的价格比明天低的时候,我们就今天买进,明天卖出,明天价格又比后天低时,我们明天再次买进,后天卖出。。。你可能觉得这不是费劲么,这样的话我今天买后天卖多省事。。。确实是这样,当时第一这不方便我们写程序,上面方法一个for loop 就能解决;其次二者的结果一样,比如有股票序列[1,4,7], 上诉方法利润是 (4-1)+(7-4) == 7-1 == 6.
(画一个股票价格折线图更清晰哟)
cpp的approach如下:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() <= 1)
return 0;
int maxprofit = 0;
for(int i = 1; i < prices.size(); ++i){
if(prices[i]-prices[i-1] > 0){
maxprofit += (prices[i]-prices[i-1]);
}
}
return maxprofit;
}
};