美文网首页
股票的最大利润

股票的最大利润

作者: 曾大稳丶 | 来源:发表于2022-05-06 10: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)。

    相关文章

      网友评论

          本文标题:股票的最大利润

          本文链接:https://www.haomeiwen.com/subject/civayrtx.html