123. Best Time to Buy and Sell Stock III(dp)
2016-09-20 17:22
330 查看
题目:
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).
同上,可以但是只能买两次
设状态f(i)表示区间[0,i-1]上的最大利润,设置状态g(i),表示区间[i,n-1]上最大利润。则最大利润为max{f(i)+g(i)};
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length<2)return 0;
int max = 0;
int n = prices.length;
int[] l = new int
;
int[] r = new int
;
int min = prices[0];
for(int i=1;i<n;i++)
{
min = Math.min(prices[i], min);
l[i]=Math.max(prices[i]-min, l[i-1]);
}
int maxx = prices[n-1];
for(int i=n-2;i>=0;i--)
{
maxx= Math.max(prices[i], maxx);
r[i]=Math.max(maxx-prices[i], r[i+1]);
}
for(int i=0;i<n;i++)
{
max = Math.max(max, r[i]+l[i]);
}
return max;
}
}
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).
同上,可以但是只能买两次
设状态f(i)表示区间[0,i-1]上的最大利润,设置状态g(i),表示区间[i,n-1]上最大利润。则最大利润为max{f(i)+g(i)};
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length<2)return 0;
int max = 0;
int n = prices.length;
int[] l = new int
;
int[] r = new int
;
int min = prices[0];
for(int i=1;i<n;i++)
{
min = Math.min(prices[i], min);
l[i]=Math.max(prices[i]-min, l[i-1]);
}
int maxx = prices[n-1];
for(int i=n-2;i>=0;i--)
{
maxx= Math.max(prices[i], maxx);
r[i]=Math.max(maxx-prices[i], r[i+1]);
}
for(int i=0;i<n;i++)
{
max = Math.max(max, r[i]+l[i]);
}
return max;
}
}
相关文章推荐
- 123:Best Time to Buy and Sell Stock III【数组】【DP】
- 【Leetcode】Best Time to Buy and Sell Stock III (DP)
- LeerCode 123 Best Time to Buy and Sell Stock III之O(n)解法
- LeetCode(123) Best Time to Buy and Sell Stock III (Java)
- Lettcode_123_Best Time to Buy and Sell Stock III
- leetcode解题报告:123 Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- LeetCode 123 Best Time to Buy and Sell Stock III
- leetcode || 123、Best Time to Buy and Sell Stock III
- [leetcode][DP] Best Time to Buy and Sell Stock III
- LeetCode 123 Best Time to Buy and Sell StockIII
- 【数组&DP】Best Time to Buy and Sell Stock III
- [LeetCode]123 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 123 Best Time to Buy and Sell Stock III
- [leetcode 123] Best Time to Buy and Sell Stock III
- Leetcode_123_Best Time to Buy and Sell Stock III
- [LeetCode 123] - 买入与卖出股票的最佳时机III(Best Time to Buy and Sell Stock III)
- Leetcode#123 Best Time to Buy and Sell Stock III