码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 121 Best Time to Buy and Sell Stock

时间:2016-03-13 18:01:58      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/fisherinbox/p/5272378.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!