[leetcode]Best Time to Buy and Sell Stock III
Posted on 2014-01-06 21:54 1957 阅读(195) 评论(0) 编辑 收藏 举报本来想枚举断开点,然后像I那样算,然后加起来求最大就好了。。。
但是TLE。。。
想了下,其实枚举断开点,重复计算了好多。。。
那就先记录下来就好了。。。
f,g两个数组,分别记录左右两边的最大值。。。
然后再枚举。。。
class Solution { public: int maxProfit(vector<int> &prices) { int size = prices.size(); if(size < 2) return 0; vector<int> f(size , 0); //left vector<int> g(size , 0); // right; //init f int profit = 0; int currmin = prices[0]; for(int i = 1 ; i < size ; i++){ profit = max(profit , prices[i] - currmin); currmin = min(currmin , prices[i]); f[i] = profit; } //init g int currmax = prices[size-1]; profit = 0; for(int i = size - 1 ; i >= 0 ; i --){ profit = max(profit , currmax - prices[i]); currmax = max(currmax , prices[i]); g[i] = profit; } profit = 0; for(int i = 0 ; i < size ; i ++){ profit = max(profit , f[i] + g[i]); } return profit; } };
by 1957