Leetcode 121 Best Time to Buy and Sell Stock

Posted fisherinbox

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 121 Best Time to Buy and Sell Stock相关的知识,希望对你有一定的参考价值。

public class S121 {
    public int maxProfit(int[] prices) {
        //TLE
/*      if(prices.length<2)
            return 0;
        int result = Integer.MIN_VALUE;        
        for(int i = prices.length-1;i>0;i--){
            prices[i] = prices[i]-prices[i-1];
        }
        for(int i = 1;i<prices.length-1;i++){
            int temp = 0;
            for(int j = i+1;j<prices.length;j++){
                temp += prices[j];
                if(temp>result)
                    result = temp;                
            }
        }
        return result;*/
        //分治法--来自算法导论最大子数组问题,AC but slow ,move findCrossMax() inside findMax() makes 3ms quicker
        //not best
/*        if(prices.length<2)
            return 0;      
        for(int i = prices.length-1;i>0;i--){
            prices[i] = prices[i]-prices[i-1];
        }
        int ret = findMax(prices,1,prices.length-1);
        return ret>0?ret:0;
    }
    public int findMax(int[] prices,int low,int high){
        if(low==high){
            return prices[low];
        }
        int left = findMax(prices,low,(low+high)/2);
        int right = findMax(prices,(low+high)/2+1,high);
//        int mid = findCrossMax(prices,low,high);
        int leftResult = Integer.MIN_VALUE;
        int rightResult = Integer.MIN_VALUE;
        int temp = 0;
        for(int i = (low+high)/2;i>low-1;i--){
            temp = temp+prices[i];
            if(temp>leftResult){
                leftResult = temp;
            }
        }
        temp = 0;
        for(int i = (low+high)/2+1;i<high+1;i++){
            temp = temp+prices[i];
            if(temp>rightResult){
                rightResult = temp;
            }
        }
        int mid = leftResult+rightResult;
        return Math.max(left, Math.max(right, mid));*/
        //best one 
        if(prices.length<2)
            return 0;
        int curMin = prices[0];
        int ret = Integer.MIN_VALUE;
        for(int i = 1;i<prices.length;i++){
            curMin = Math.min(curMin, prices[i]);
            ret = Math.max(ret, prices[i]-curMin);
        }
        return ret;
    }    
}

 

以上是关于Leetcode 121 Best Time to Buy and Sell Stock的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode OJ 121. Best Time to Buy and Sell Stock

Leetcode 121 Best Time to Buy and Sell Stock

Leetcode121. Best Time to Buy and Sell Stock

LeetCode 121: Best Time to Buy and Sell Stock

LeetCode 121 Best Time to Buy and Sell Stock

Leetcode 121. Best Time to Buy and Sell Stock