[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数组
然后对所有的
【附】
第9行与第10行、第13行与第14行是可以上下交换的。
【代码】
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] Best Time to Buy and Sell Stock III
- Leetcode---Best Time to Buy and Sell Stock III
- [leetcode]Best Time to Buy and Sell Stock III @ Python
- leetcode123. [DP]Best Time to Buy and Sell Stock III
- leetcode 16: Best Time to Buy and Sell Stock III
- leetcode 123: Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III -- LeetCode
- LeetCode-Best Time to Buy and Sell Stock III算法对比
- LeetCode 123. Best Time to Buy and Sell Stock III| 动态规划
- leetcode123 Best Time to Buy and Sell Stock III
- Leetcode Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III 最佳时间买入卖出股票(最多两次买卖)@LeetCode
- LeetCode123—Best Time to Buy and Sell Stock III
- [LeetCode]123 Best Time to Buy and Sell Stock III
- Leetcode 贪心 Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- LeetCode: Best Time to Buy and Sell Stock III [123]
- LeetCode Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III leetcode java