121. Best Time to Buy and Sell Stock - Easy

前往題目

之前寫的文章

思路

  1. sliding window
  2. 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/
作者
Simon Lai
發布於
2024年1月31日
許可協議