题目
Say you have an array for which the i-th 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 (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
题目
一个列表,每个元素值表示第i 天第股票价格,可以做任意笔交易(即买入和卖出),但是必须是
买入->卖出->买入->卖出->…
这样的顺序,不可完成两次连续的买入操作
程序输入输出式例:
Example 1:
输入: [7,1,5,3,6,4]
输出: 7
解释: 第2天买入(价格=1),第3天卖出(价格=5),第4天买入(价格=3),第5天卖出(价格=6)
利润=4+3=7
Example 2:
输入: [1,2,3,4,5]
输出: 4
解释:第1天买入,第5天卖出,利润=4
Example 3:
输入: [7,6,4,3,1]
输出: 0
解释:
解析
使用贪心算法进行求解,不过使用时需要进行一定的思路转变,在第i天买入时,如果第i+1天第价格上涨,则卖出,并累加利润。
int maxProfit(vector<int>& prices) {
if(prices.size()<=1) // 数组长度为1时,不买入
return 0;
int result=0;
for(int i=0;i<prices.size()-1;i++){
if(prices[i+1]>prices[i])
result+=(prices[i+1]-prices[i]);
}
return result;
刚看到这道题的想法是很混乱的,因为会有多种买入卖出的方法,但拿笔在纸上画一画之后,发现相邻两天之间的利润之和便等于最大利润,注意,在同一天是可以进行两种操作的,即在第i天卖出后仍可以买入,所以不能以为一天只能有一种操作。
理解
在一个递增数组中,[a,b,c,d…z] , 最大差值=z-a=z-y+y-x+x-w+…+b-a
所以该题的数组可以拆分成多个递增数组的组成,拆分点是 prices[i]<prices[i+1]
最终结果=所有递增数组的最大差值之和