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;
        }
    }
    
  • 相关阅读:
    docker 安装 mysql5.7
    docker 安装 redis
    docker 安装 gitlab
    docker 升级到新版本
    logstash 采集springboot 错误日志配置
    图片左下角添加水印
    frida动态修改
    反反frida调试
    IDA插件KeyPatch直接在IDA中修改arm指令
    frida调用制作dex(用于有些对象读取不了)
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13860004.html
Copyright © 2011-2022 走看看