标签:
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).
最多只能购买两次,那么以i为划分,计算以i结尾的左边子数组的最大交易,和以i开头的右边子数组的最大交易。
问题转换为求两个子数组的最大利益,这个就是Best Time to Buy and Sell Stock I,总的时间复杂度是O(n^2);
再做优化,先从左到右计算以i结尾的最大利益,这个可以在o(n)的时间内完成,
然后从末尾开始往前遍历,计算从[n,i]的最大利益。
那么最大利益就是在i这个划分上的左边的最大+右边的最大。
其实这个题和还有一个题很相似,就是,以A[1..n]数组构造B[1..n],使得B[i]=A[1]*A[2]*...*A[i-1]*A[i+1]*...A[n];
class Solution { public: int maxProfit(vector<int>& prices) { int pricesSize = prices.size(); if(pricesSize<=1){ return 0; } int lowPrice = prices[0]; vector<int> maxProfits(pricesSize,0); for(int i=1;i<pricesSize;i++){ maxProfits[i] = max(prices[i] - lowPrice,maxProfits[i-1]); lowPrice = min(lowPrice,prices[i]); } int maxProfit = maxProfits[pricesSize-1],rightMaxProfit=0; int highPrice = prices[pricesSize-1]; for(int i=pricesSize-2;i>=0;i--){ rightMaxProfit = max(highPrice - prices[i],rightMaxProfit); maxProfit = max(maxProfit,max(maxProfits[i]+rightMaxProfit,maxProfits[i])); highPrice = max(highPrice,prices[i]); } return maxProfit; } };
Best Time to Buy and Sell Stock III
标签:
原文地址:http://www.cnblogs.com/zengzy/p/5004785.html