题目描述
给定一个数组prices, prices[i]表示第i天股票的股价,现在你可以在某一天买一次股票,在后面的另外一天再把股票卖了,那么中间的差价prices[j]-proces[i]就是你赚取的利润。现在你可以买一次,卖一次,然后再买,再卖,但是必须保证下次再买的时候,手上的股票已经卖了。求在这种情况下,利润的最大值。
解题分析
这题其实要比之前那个题目121题简单一点,这题用贪心算法就可以解决。只要prices[i]比prices[i-1]大,那么第i-1天的时候买,第i天的时候卖,就构成了一次交易。这样,只需要把所有后一个数比前一个数大的情况全部加起来就可以了。
class Solution {
public int maxProfit(int[] prices) {
if (prices.length < 2) {
return 0;
}
int totalProfit = 0;
for (int i = 1; i < prices.length; i++){
int currentProfit = prices[i] - prices[i-1];
if (currentProfit > 0){
totalProfit += currentProfit;
}
}
return totalProfit;
}
}