目录
- 2023-8-10 10:29:32
122. 买卖股票的最佳时机 II
2023-8-10 10:29:32
没错,还是用双指针思想来套出来的。
感觉步骤很复杂,还调试了半天。
class Solution {
public int maxProfit(int[] prices) {
int pre = 0;
int last = 1;
int maxProfit = 0;
int currentProfit = 0;
while (last < prices.length) {
if (prices[pre] >= prices[last] || prices[last] < prices[last - 1]) {
maxProfit = maxProfit + currentProfit;
currentProfit = 0;
pre = last;
} else {
int temp = prices[last] - prices[pre];
if (currentProfit < temp) {
currentProfit = temp;
}
}
last++;
}
return maxProfit + currentProfit;
}
}
贪婪算法:局部最优解就能够组成全局最优解
这道题呢,就是:计划在第N天买入,第N+1天卖出
最大利润就是:4 + 3 +1 = 8