LeetCode 123.Best Time to Buy and Sell Stock III
由于先做了这类题目的 I II,看到III就直接按照先求局部最大值,取最大的前两个的和。(错误的代码就不贴了。。。)后来一直wrong answer. 忽然明白了限定两手交易,仍然可能将两个局部最大值连起来组成更大数值。一时想不起来解法
看到两个算法:
1.大牛1用分治策略,移动分割点分别计算左右最大值。再加上优化就过了!http://blog.csdn.net/littlestream9527/article/details/21326153
2.在这里 http://www.tuicool.com/articles/JjAnue。 看到代码吃了一惊!大神真是兼备简要的代码而又清晰的思路。拜大神! -~-~-~-~-
原帖在github上 https://github.com/zhumeng1989/MISC/blob/nightly/common/leetcode.hpp#L611
// 123.Best Time to Buy and Sell Stock III
class Solution {
public:
int maxProfit(vector &prices) {
int maxval = 0;
int n = prices.size();
if (n <= 1) return 0;
int curmin = prices[0];
vector l2r(n,0);
for (int i=1; i
curmin = min(curmin, prices[i]);
maxval = max(maxval, prices[i]-curmin);
l2r[i] = maxval;
}
maxval = 0;
int curmax = prices[n-1];
vector r2l(n,0);
for (int i=n-2; i>=0; i--) {
curmax = max(curmax, prices[i]);
maxval = max(maxval, curmax-prices[i]);
r2l[i] = maxval;
}
maxval = 0;
for (int i=0; i
maxval = max(maxval, l2r[i]+r2l[i]);
return maxval;
}
};
由于先做了这类题目的 I II,看到III就直接按照先求局部最大值,取最大的前两个的和。(错误的代码就不贴了。。。)后来一直wrong answer. 忽然明白了限定两手交易,仍然可能将两个局部最大值连起来组成更大数值。一时想不起来解法
看到两个算法:
1.大牛1用分治策略,移动分割点分别计算左右最大值。再加上优化就过了!http://blog.csdn.net/littlestream9527/article/details/21326153
2.在这里 http://www.tuicool.com/articles/JjAnue。 看到代码吃了一惊!大神真是兼备简要的代码而又清晰的思路。拜大神! -~-~-~-~-
原帖在github上 https://github.com/zhumeng1989/MISC/blob/nightly/common/leetcode.hpp#L611
// 123.Best Time to Buy and Sell Stock III
class Solution {
public:
int maxProfit(vector &prices) {
int maxval = 0;
int n = prices.size();
if (n <= 1) return 0;
int curmin = prices[0];
vector l2r(n,0);
for (int i=1; i
curmin = min(curmin, prices[i]);
maxval = max(maxval, prices[i]-curmin);
l2r[i] = maxval;
}
maxval = 0;
int curmax = prices[n-1];
vector r2l(n,0);
for (int i=n-2; i>=0; i--) {
curmax = max(curmax, prices[i]);
maxval = max(maxval, curmax-prices[i]);
r2l[i] = maxval;
}
maxval = 0;
for (int i=0; i
maxval = max(maxval, l2r[i]+r2l[i]);
return maxval;
}
};