acbingo

121. 买卖股票的最佳时机

动态规划:前i天的最大收益 = max{前i-1天的最大收益,第i天的价格-前i-1天中的最小价格}

维护两个值即可:min,ans

class Solution {
    public int maxProfit(int[] prices) {
        int min = Integer.MAX_VALUE;
        int ans = 0;

        for (int price : prices) {
            if (price < min) {
                min = price;
            } else if (ans < price - min) {
                ans = price - min;
            }
        }
        return ans;
    }
}

分类:

技术点:

相关文章:

  • 2021-11-21
  • 2021-08-03
  • 2021-08-03
  • 2021-11-04
  • 2021-06-09
  • 2021-12-07
  • 2022-01-02
猜你喜欢
  • 2021-08-03
  • 2021-08-03
  • 2021-08-03
  • 2020-06-22
  • 2021-07-07
  • 2021-06-21
相关资源
相似解决方案