[leetcode]Best Time to Buy and Sell Stock III
2013-08-26 14:05
399 查看
- -最多可以买两次。。。最大收益。。。
第一想法,枚举分割线,然后按I那种做法来做,算两边的最大收益。
= =时间复杂度O(n^2)
其实可以这么想啦..
从刚才的枚举分割线的想法,那么我就用两个数组记录
从左到右的最大收益,另外一个是从右往左的最大收益.
那么还是枚举分割线哒!但是实践复杂度就是O(n)啦.
第一想法,枚举分割线,然后按I那种做法来做,算两边的最大收益。
= =时间复杂度O(n^2)
其实可以这么想啦..
从刚才的枚举分割线的想法,那么我就用两个数组记录
从左到右的最大收益,另外一个是从右往左的最大收益.
那么还是枚举分割线哒!但是实践复杂度就是O(n)啦.
class Solution { public: void calc(vector<int>&data , vector<int>&f){ int minx = 0; int ans = 0; f[0] = 0; for(int i = 1 ; i < data.size() ; i++){ if(data[i] < data[minx]) minx = i; int tmp = data[i] - data[minx]; ans = max (ans , tmp); f[i] = ans; } } void calc1(vector<int>&data , vector<int>&f){ int maxx = 0; int ans = 0; f[0] = 0; for(int i = 1 ; i < data.size() ; i++){ if(data[i] > data[maxx]) maxx = i; int tmp = data[maxx] - data[i]; ans = max(ans , tmp); f[i] = ans; } } int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function if(prices.size() <= 1) return 0; vector<int> f(prices.size()); vector<int> h(prices.size()); calc(prices , f); reverse(prices.begin() , prices.end()); calc1(prices , h); reverse(h.begin() , h.end()); int ans = f[f.size() - 1]; for(int i = 0 ; i < f.size() - 1 ; i ++){ ans = max(ans , f[i] + h[i+1]); } return ans; } };
相关文章推荐
- leetcode 123 —— Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III -- LeetCode
- LeetCode动态规划思想:Best Time to Buy and Sell Stock III
- 【LeetCode】Best Time to Buy and Sell Stock III
- 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告
- LeetCode | Best Time to Buy and Sell Stock III(股票购买抛售问题III)
- [LeetCODE] Best Time to Buy and Sell Stock I II III IV V
- LeetCode: Best Time to Buy and Sell Stock III
- LeetCode | Best Time to Buy and Sell Stock III
- leetcode_c++:Best Time to Buy and Sell Stock III(123)
- Best Time to Buy and Sell Stock III :from LeetCode
- Best Time to Buy and Sell Stock III ---- LeetCode
- 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
- [LeetCode] Best Time to Buy and Sell Stock III
- Leetcode刷题总结:123. Best Time to Buy and Sell Stock III
- LeetCode OJ Best Time to Buy and Sell Stock I II III IV
- leetcode Best Time to Buy and Sell Stock(I~III)(*)
- leetcode Best Time to Buy and Sell Stock III