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

    解法

    思路:先查找整个区间的最大峰值,再查找该区间之前的最小值,计算利润,
    然后缩小区间,查找峰值与最小值,再次计算并更新利润。

    class Solution {
        public int maxProfit(int[] prices) {
           int lo = 0, hi = prices.length - 1;
           int profit = 0;
           while(hi > lo){
               int max = lo;
               for(int i = lo; i <= hi; i++){//查找整个区间最大值
                   if(prices[i] > prices[max]) max = i;
               }
               int min = lo;
               for(int i = lo; i < max; i++){//查找当前区间最大值之前的最小值
                   if(prices[i] < prices[min]) min = i;
               }
               if(prices[max] - prices[min] > profit){//计算差值进行更新
                   profit = prices[max] - prices[min];
               }
               lo = max + 1;//缩小区间范围继续
           }
           return profit;
        }
    }
    

    一次遍历

    class Solution {
        public int maxProfit(int[] prices) {
            int min = 0;
            int maxP = 0;
            for(int i = 1; i < prices.length; i++) {
                if(prices[i] < prices[min]){
                    min = i;
                }else{
                    if(prices[i] - prices[min] > maxP){
                        maxP = prices[i] - prices[min];
                    }
                }
            }
            return maxP;
        }
    }
    
    class Solution {
        public int maxProfit(int[] prices) {
            int min = Integer.MAX_VALUE;
            int maxP = 0;
            for(int i = 0; i < prices.length; i++) {
                if(prices[i] < min){
                    min = prices[i];
                }else{
                    if(prices[i] - min > maxP){
                        maxP = prices[i] - min;
                    }
                }
            }
            return maxP;
        }
    }
    
  • 相关阅读:
    C语言---堆的实现
    python的matplotlib---雷达图
    python的matplotlib饼状图
    python的matplotlib折线图
    python的matplotlib散点图学习
    python的matplotlib散点图
    C语言---队列(链表实现)
    hadoop集群启动与关闭需要输入密码
    hadoop集群启动时需要输入密码
    C语言---堆栈(链表实现)
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13860004.html
Copyright © 2011-2022 走看看