一、题目
力扣原题:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
二、峰谷法
class Solution {
public int maxProfit(int[] prices) {
int result = 0;
int i = 0;
while (i < prices.length - 1) {
// 找到下一个谷
while (i < prices.length - 1 && prices[i] >= prices[i + 1]) {
i++;
}
int low = prices[i];
// 找到下一个峰
while (i < prices.length - 1 && prices[i] < prices[i + 1]) {
i++;
}
int high = prices[i];
result = result + (high - low);
}
return result;
}
}
- 基本思路:通过股票价格的折线图,可以知道若想达到收益的最大化,不能错过每一段上升的曲线。在每段上升曲线的最低处购入股票,并在最高处出售股票即可。
- 时