标签:
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).
动态规划,preprofit保存i之前交易获得的收益。postprofit保存i之后交易获得的收益。
max{preprofit[i]+postprofit[i]}既是最大的可能收益。
class Solution { public: int maxProfit(vector<int>& prices) { int size=prices.size(); if (size<2) return 0; int curmin=prices[0],curmax=prices[size-1]; vector<int> preProfit(size,0); vector<int> postProfit(size,0); for(int i=1;i<size;i++){ curmin=min(curmin,prices[i]); preProfit[i]=max(preProfit[i-1],prices[i]-curmin); } for (int j = size-1;j>0; --j){ curmax=max(curmax,prices[j]); postProfit[j]=max(postProfit[j-1],curmax-prices[j]); } int retProfit=0; for(int m=0;m<size;m++){ if(retProfit<(preProfit[m]+postProfit[m])) retProfit=preProfit[m]+postProfit[m]; } return retProfit; } };
[leetcode]123. Best Time to Buy and Sell Stock III
标签:
原文地址:http://www.cnblogs.com/LUO77/p/5631768.html