股票的最大利润

2022-05-06  本文已影响0人  曾大稳丶

题目链接:https://leetcode-cn.com/problems/gu-piao-de-zui-da-li-run-lcof/

image.png

题目解析

  1. 暴力解析,两次for循环计算。
    代码省略
    复杂度分析
    空间复杂度: O(n^2)。
    时间复杂度: O(1)。

  2. 一次遍历,遍历的时候记录最小的值和当前计算得到最大的结果即可。

  public int maxProfit(int[] prices) {
      if (prices == null){
            return 0;
        }
        int max = 0;
        int min = Integer.MAX_VALUE;
        for (int price : prices) {
             if (price < min){
                 min = price;
             }else {
                 max = Math.max(max,price-min);
             }
        }
        return max;
  }

复杂度分析
空间复杂度: O(n)。
时间复杂度: O(1)。

上一篇下一篇

猜你喜欢

热点阅读