Title Link: click~
/* Test instructions: An array, the element I represents the price of the stock of day I, allow up to two times to buy and sell, for maximum profit *//** * idea: Record the maximum profit of the day with the Currprofit array, scan the array from start to finish to get the * Currprofit = max (Currpor Fit[i], prices[i]-low) * * Record the maximum profit after the day with a futureprofit array, from the tail to the end of the scan can be * futureprofit = max (Futureprofit[i], high-prices [i]) * * Calculate total Profit: Anx = max (ans, currprofit[i]+futureprofit[i]) */class Solution {Public:int Maxprofit (vector<int > &prices) {int len = prices.size (); if (Len <= 1) return 0; int *currprofit = new Int[len]; int *futureprofit = new Int[len]; Currprofit[0] = futureprofit[len-1] = 0; Record the maximum profit for the cutoff date int low = Prices[0]; for (int i = 1; i < Len; i + +) {low = min (Low, prices[i]); Currprofit[i] = max (currprofit[i-1], prices[i]-low); }//Calculate the maximum profit after the day int high = prices[len-1]; for (int i = len-2; I >= 0; I-) {high = max (high, prices[i]); Futureprofit[i] = max (futureprofit[i+1], high-prices[i]); } Total int ans = 0; for (int i = 0; i < len; i + +) ans = max (ans, currprofit[i] + futureprofit[i]); return ans; }};
123:best time to Buy and Sell Stock III "Array" "DP"