121. Best Time to Buy and Sell Stock - Easy
前往題目
之前寫的文章
思路
sliding window
high
指針一直往右,遇到low
指針的值比high
還大就把low
直接移過去high
,代表找到更小值了
Code
class Solution {
public int maxProfit(int[] prices) {
int low = 0, high = 0;
int res = 0;
while (high < prices.length) {
// Update profit
res = Math.max(res, prices[high] - prices[low]);
// Found lower number
if (prices[high] < prices[low]) {
low = high;
}
++high;
}
return res;
}
}
121. Best Time to Buy and Sell Stock - Easy
https://f88083.github.io/2024/01/31/121-Best-Time-to-Buy-and-Sell-Stock-Easy/