[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;
    }
}
posted @ 2020-07-13 10:14  消灭猕猴桃  阅读(61)  评论(0编辑  收藏  举报