使用连续的波峰减去波谷
比如:[7, 1, 5, 3, 6, 4]
画成折线图如下
连续波峰波谷之间差的和即为最大的利润,代码如下,仍然要注意输入为空的情况
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0) return 0;
int i = 0;
int valley = prices[0];
int peak = prices[0];
int sum = 0;
while(i < prices.length - 1){
if(i < prices.length - 1 && prices[i] >= prices[i + 1])
i++;
valley = prices[i];
if(i < prices.length - 1 && prices[i] <= prices[i + 1])
i++;
peak = prices[i];
sum = sum + (peak - valley);
}
return sum;
}
}