题目传送: ​​https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/​

运行效率:

Leetcode122. 买卖股票的最佳时机 II_算法


代码如下:

class Solution {
public int maxProfit(int[] prices) {
int maxProfit=0;
int left = 0;
int right = 1;
//找到所有的上升段即可,把这些上升段加起来即可
while (right < prices.length) {
if (prices[left] < prices[right]) {
while (right + 1 < prices.length && prices[right] < prices[right + 1]) {
right++;
}
maxProfit+=prices[right]-prices[left];
left=right+1;
right=left+1;
} else {
left++;
right++;
}
}
return maxProfit;
}
}