[LeetCode10]Best Time to Buy and Sell Stock III

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).


Analysis

One dimensional dynamic planning.the max profit at day i is the max profit before day i + max profit after day i.
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

Java

public int maxProfit(int[] prices) {
        int maxPro = 0;
		if(prices.length>1){
			ArrayList<Integer> mp = new ArrayList<>();
			int minP = prices[0];
			mp.add(maxPro);
			for(int i=1;i<prices.length;i++){
				if(prices[i]-minP>=maxPro){ 
					maxPro = prices[i]-minP;
				}
				if(minP>prices[i]) minP = prices[i];
				mp.add(maxPro);
			}
			maxPro =0;
			int maxP = prices[prices.length-1];
			for(int i=prices.length-2;i>=0;i--){
				if(maxPro<maxP-prices[i]+mp.get(i)){
					maxPro = maxP-prices[i]+mp.get(i);
				}
				if(prices[i]>maxP) maxP = prices[i];
			}
		}
		return maxPro;
    }


c++

int maxProfit(vector<int> &prices){
    if(prices.size()<=1) return 0;
    if(prices.size()==2) return prices[1]>prices[0]?prices[1]-prices[0]:0;
    vector<int> maxFromLeft(prices.size(),0);
    vector<int> maxFromRight(prices.size(),0);
    int minL = INT_MAX, max=INT_MIN, diff;
    for(int i=0;i<prices.size();i++){
        if(prices[i]<minL) minL = prices[i];
        diff = prices[i]- minL;
        if(diff >max)
            max = diff;
        maxFromLeft[i] = max;
    }
    int maxR = INT_MIN;
    max = INT_MIN;
    for(int i=prices.size()-1;i>=0;i--){
        if(prices[i]>maxR) maxR = prices[i];
        diff = maxR - prices[i];
        if(diff > max)
            max = diff;
        maxFromRight[i] = max;
    }
    max = INT_MIN;
    for(int i=0;i<prices.size()-1;i++){
        int diff = maxFromLeft[i]+maxFromRight[i+1];
        if(diff > max) max = diff;
    }
    if(max < maxFromRight[0])
        max = maxFromRight[0];
    return max;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值