Best Time to Buy and Sell Stock III
2013-10-01 00:35
309 查看
很经典啊,先从前往后来一遍,再从后往前来一遍,最后得到结果。
class Solution { public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function int len=prices.size(); if(len==0||len==1) return 0; vector<int> forward; vector<int> back; forward.assign(len,0); back.assign(len,0); int vally=prices[0]; for(int i=0;i<len;i++){ vally=min(vally,prices[i]); if(i>0){ forward[i]=max(forward[i-1],prices[i]-vally); } } int res=0; int peak=prices[len-1]; for(int i=len-1;i>=0;i--){ peak=max(peak,prices[i]); if(i<len-1){ back[i]=max(back[i+1],peak-prices[i]); } res=max(res,forward[i]+back[i]); } return res; } };
相关文章推荐
- 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题解: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 I II III
- 123. Best Time to Buy and Sell Stock III
- leetcode 123. Best Time to Buy and Sell Stock III 最大k次字段和 + DP
- 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
- 123. Best Time to Buy and Sell Stock III(dp)
- Best Time to Buy and Sell Stock III(JAVA)-动态规划
- 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告
- 4 Best Time to Buy and Sell Stock III_Leetcode
- 【LeetCode】Best Time to Buy and Sell Stock I && II && III
- leetcode:Best Time to Buy and Sell Stock III
- Algorithms(十二)Best Time to Buy and Sell Stock III
- 【LeetCode】 Best Time to Buy and Sell Stock III
- 111_leetcode_Best Time to Buy and Sell Stock III