面试经典 150 题 (七)

从右往左遍历

class Solution {
    public int maxProfit(int[] prices) {
        Map<Integer, Integer> priceMap = new HashMap<Integer, Integer>();
        Integer leftMaxNum = null;
        for (int i = prices.length - 1; i >= 0; i--){
            if (leftMaxNum == null || leftMaxNum < prices[i]){
                leftMaxNum = prices[i];
            }
            priceMap.put(prices[i], leftMaxNum);
        }
        int maxMom = 0;
        for (Map.Entry<Integer, Integer>price : priceMap.entrySet()){
            if ((price.getValue() - price.getKey()) > maxMom){
                maxMom = price.getValue() - price.getKey();
            }
        }
        return maxMom;
    }
}

不用hashMap版本

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length <= 1){
            return 0;
        }
        int leftMaxPrices[] = new int[prices.length];
        int leftMax = 0;
        for (int i = prices.length - 1; i >= 0; i--){
            if(prices[i] > leftMax){
                leftMax = prices[i];
            }
            leftMaxPrices[i] = leftMax;
        }
        int maxPro = 0;
        for (int i = 0; i < prices.length; i++){
            if (maxPro < leftMaxPrices[i] - prices[i]){
                maxPro = leftMaxPrices[i] - prices[i];
            }
        }
        return maxPro;
    }
}

从左向右,记录当前最小的价格

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length <= 1){
            return 0;
        }
        int minPrice = prices[0];
        int maxPro = 0;
        for (int i = 1; i < prices.length; i++){
            if (minPrice > prices[i]){
                minPrice = prices[i];
            }
            if((prices[i] - minPrice) > maxPro){
                maxPro  = prices[i] - minPrice;
            }
        }
        return maxPro;
    }
}
posted @ 2024-01-27 20:45  破忒头头  阅读(19)  评论(0)    收藏  举报