您的位置:首页 > 其它

[LeetCode]Best Time to Buy and Sell Stock III

2016-11-29 16:21 477 查看
Question

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

本题难度Hard。

DP

【题意】

最多可以进行两次交易,求最大利润。

【复杂度】

时间 O(N) 空间 O(N)

【思路】

我们仍然用反推法来得到算法。有以下几种可能:



可以看出,两次交易的分隔毫无规律,实际上也就意味着求两次交易的最大利润是用遍历的办法找出来的。我们利用DP的方法,分别利用两个DP数组
f
g




然后对所有的
i
遍历求出最大的
f[i]+g[i]
就是我们要的答案。

【附】

第9行与第10行、第13行与第14行是可以上下交换的。

【代码】

public class Solution {
public int maxProfit(int[] prices) {
//require
int size=prices.length;
if(size<1)return 0;
int[] f=new int[size],g=new int[size];
//invariant
for(int i=1,valley=prices[0];i<size;i++){
valley=Math.min(valley,prices[i]);
f[i]=Math.max(f[i-1],prices[i]-valley);
}
for(int i=size-2,peak=prices[size-1];i>=0;i--){
peak=Math.max(peak,prices[i]);
g[i]=Math.max(g[i+1],peak-prices[i]);
}
int maxProfit=0;
for(int i=0;i<size;i++)
maxProfit=Math.max(maxProfit,f[i]+g[i]);
//ensure
return maxProfit;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法