您的位置:首页 > 其它

leetcode 123. Best Time to Buy and Sell Stock III

2016-07-25 15:41 309 查看
传送门

123. Best Time to Buy and Sell Stock III

QuestionEditorial Solution
My Submissions

Total Accepted: 62311

Total Submissions: 230292

Difficulty: Hard

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

Subscribe to see which companies asked this question

Hide Tags

Array Dynamic Programming

Show Similar Problems

思路:
思想来源于动态规划,如果以arr[i]为第二个投资点,那么,必须找到i-1前面的最大投资收益
so,,,左右各dp一次。。。

class Solution {
public:
int maxProfit(vector<int>& prices) {
int sz = prices.size();
vector<int> left(sz + 1,0);
int i;
int mi = INT_MAX;
for(i = 0;i < sz;i++){
if(i != 0){
left[i] = left[i - 1];
}
if(prices[i] < mi){
mi = prices[i];
}
else{
left[i] = max(left[i],prices[i] - mi);
}
}

vector<int> right(sz + 1,0);
int ma = INT_MIN;
for(i = sz - 1;i >= 0;i--){
if(i != sz - 1){
right[i] = right[i + 1];
}
if(prices[i] > ma){
ma = prices[i];
}
else{
right[i] = max(right[i],ma - prices[i]);
}
}
//for(i = 0;i < sz;i++){
//    printf(" i = %d left = %d right = %d\n",i,left[i],right[i]);
//}

int ma_profile = left[sz - 1];
for(i = 0;i < sz - 1;i++){
ma_profile = max(ma_profile,left[i] + right[i + 1]);
}
return ma_profile;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: