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).
class Solution { public: int maxProfit(vector<int> &prices) { if(prices.size() == 0) return 0; int maxProfit = 0; int maxp1 = 0; int maxp2 = 0; int minp1 = prices[0]; int minp2 = INT_MAX; for(int i = 1;i < prices.size();i++){ int diff1 = prices[i] - minp1; if(diff1 < 0){ minp1 = prices[i]; }else if(diff1 > maxp1){ maxp1 = diff1; } if(i < prices.size() - 1){ for(int j = i; j < prices.size();j++){ int diff2 = prices[j] - minp2; if(diff2 < 0){ minp2 = prices[j]; }else if(diff2 > maxp2){ maxp2 = diff2; } } }else{ maxp2 = 0; } maxProfit = (maxp1 + maxp2) > maxProfit ? maxp1 + maxp2:maxProfit; } return maxProfit; } };
LeetCode: Best Time to Buy and Sell Stock III,布布扣,bubuko.com
LeetCode: Best Time to Buy and Sell Stock III
原文:http://www.cnblogs.com/yeek/p/3578619.html