首页 > 其他 > 详细

Best Time to Buy and Sell Stock III

时间:2014-02-18 08:02:21      阅读:325      评论:0      收藏:0      [点我收藏+]

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Ref:http://fisherlei.blogspot.com/2013/01/leetcode-best-time-to-buy-and-sell_3958.html

http://www.cnblogs.com/jasonC/p/3417722.html

[Thoughts]

前后两遍遍历,算出当前位置之前和之后的最大利润。

One dimensional dynamic planning.
Given an i, split the whole array into two parts:
[0,i] and [i+1, n], it generates two max value based on i, Max(0,i) and Max(i+1,n)
So, we can define the transformation function as:
Maxprofix = max(Max(0,i) + Max(i+1, n))  0<=i<n
Pre-processing Max(0,i) might be easy, but I didn‘t figure an efficient way to generate Max(i+1,n) in one pass.

bubuko.com,布布扣
public class Solution {
    public int maxProfit(int[] prices) {
        
        if(prices == null || prices.length == 0)
            return 0;
            
        int[] max = new int[prices.length];
        int min = prices[0];
        int result = 0;
        
        for(int i = 1; i < prices.length; i++){
            min = Math.min(min, prices[i]);
            max[i] = Math.max(max[i-1], prices[i] - min);
        }
        
        int peek = Integer.MIN_VALUE;
        for(int i = prices.length-1; i >= 0; i--){
            
            peek = Math.max(prices[i],peek);
            result = Math.max(result, peek - prices[i] + max[i]);
        }
        return result;
    }
}
bubuko.com,布布扣

Best Time to Buy and Sell Stock III

原文:http://www.cnblogs.com/RazerLu/p/3552842.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!