zoukankan      html  css  js  c++  java
  • 121. 买卖股票的最佳时机

     思路:可以找出数组里每一个元素右侧的最大值,再遍历整个数组,找当前元素右侧最大值和当前元素数值的差,最大的就是要求的结果。

    class Solution {
        public int maxProfit(int[] prices) {
            int[] rightMax=new int[prices.length];
    
            for(int i=prices.length-2;i>=0;i--)
            {
                rightMax[i]=Math.max(rightMax[i+1],prices[i+1]);
            }
            int max=0;
            for(int i=0;i<prices.length;i++)
            {
                if(rightMax[i]-prices[i]>max)
                {
                    max=rightMax[i]-prices[i];
                }
    
            }
            return max;
        }
    }
    

      思路2:

    public class Solution {
        public int maxProfit(int prices[]) {
            int minprice = Integer.MAX_VALUE;//目前最低价格
            int maxprofit = 0;
            for (int i = 0; i < prices.length; i++) {
                if (prices[i] < minprice)//如果今天的价格比最低的还要低,更新最低价格
                    minprice = prices[i];
                else if (prices[i] - minprice > maxprofit)//计算当前差值,如果比当前的最大差值还要大,就更新当前最大差值
                    maxprofit = prices[i] - minprice;
            }
            return maxprofit;
        }
    }
    
    作者:LeetCode-Solution
    链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/solution/121-mai-mai-gu-piao-de-zui-jia-shi-ji-by-leetcode-/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    

      

  • 相关阅读:
    大数乘法
    大数阶乘
    存js导入excel文件
    设计模式详解
    javascript的api设计原则
    从零开始nodejs系列文章
    git的学习
    如何暴力学英语
    Vsftpd
    shell命令学习
  • 原文地址:https://www.cnblogs.com/lzh1043060917/p/12880704.html
Copyright © 2011-2022 走看看