题目描述
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).
解题思路
题目意思是一个包含n个元素的整型数组,其中的第i个元素是指定股票在第i天的价格。计算在这n天里可能获得的最大利润。注:只考虑单只该股票的买入和卖出时机,一天内可以买卖多次,但不允许同一时间内存在多次交易(即:再次买入之前,必须买入该股票)
一种贪心的策略是不考虑全局的是什么情况,只考虑第二天和今天的对比,如果第二天比今天的股价高,则今天买入,且买入后的第二天股价上涨,就卖出;同时如果后一天股价下跌则前一天不买入。
分析贪心的正确性(原文链接:http://www.jianshu.com/p/34bbb0594bd9):
本题由于是可以操作任意次数,只为获得最大收益,而且对于一个上升子序列,比如:[5, 1, 2, 3, 4]中的1, 2, 3, 4序列来说,对于两种操作方案:
1 在1买入,4卖出
2 在1买入,2卖出同时买入,3卖出同时买入,4卖出
这两种操作下,收益是一样的。
复杂度分析
时间复杂度为O(N),只要扫描一遍数值即可。
代码如下:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sum=0;
for (int i=1; i<prices.size(); i++) {
if (prices[i]-prices[i-1]>0) {
sum+=prices[i]-prices[i-1];
}
}
return sum;
}
};