您的位置:首页 > 其它

LeetCode - Best Time to Buy and Sell Stock III

2014-01-13 01:46 369 查看
Best Time to Buy and Sell Stock III

2014.1.13 01:43

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

Solution:

  This problem is a variation from Best Time to Buy and Sell Stock. The difference lies in that you can make two transactions, instead of only one.

  In that problem, we pointed out a solution using dynamic programming, done in linear time complexity. Note that the DP can be done either from front to rear, or from rear to front, different code but same outcome.

  In this problem, we'll do both, i.e. do the DP from both ends and let them meet up in the middle.

  Time complexity is doubled, as you can do two transactions. Space complexity is raised from O(1) to O(n), since you have to record the intermediate results and scan for the maximum sum in the end.

Accepted code:

// 1RE, 1WA, 1AC, good
class Solution {
public:
int maxProfit(vector<int> &prices) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.

// 1RE here, didn't take empty array into account
if(prices.size() <= 0){
return 0;
}

int *a1, *a2;
int n;
int i, mv;

n = prices.size();
a1 = new int
;
a2 = new int
;

a1[0] = 0;
mv = prices[0];
for(i = 1; i < n; ++i){
if(prices[i] < mv){
mv = prices[i];
}
// 1WA here, prices[i] not a1[i]
a1[i] = prices[i] - mv > a1[i - 1] ? prices[i] - mv : a1[i - 1];
}

a2[n - 1] = 0;
mv = prices[n - 1];
for(i = n - 2; i >= 0; --i){
if(prices[i] > mv){
mv = prices[i];
}
a2[i] = mv - prices[i] > a2[i + 1] ? mv - prices[i] : a2[i + 1];
}

mv = a1[0];
for(i = 1; i < n; ++i){
if(a1[i] > mv){
mv = a1[i];
}
}

for(i = 0; i < n; ++i){
if(a2[i] > mv){
mv = a2[i];
}
}

for(i = 0; i < n - 1; ++i){
if(a1[i] + a2[i + 1] > mv){
mv = a1[i] + a2[i + 1];
}
}

delete[] a1;
delete[] a2;
a1 = nullptr;
a2 = nullptr;

return mv;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: