Say you have an array for which the ith element is the price of a given stock on day i.spa
Design an algorithm to find the maximum profit. You may complete at most two transactions.code
class Solution { public: int maxProfit(vector<int>& prices) { int len=prices.size(); if(len<=0) return 0; vector<int> left(len); vector<int> right(len); int min=prices[0]; for(int i=1;i<len;i++) { min=prices[i]<min?prices[i]:min; left[i]=prices[i]-min>left[i-1]?prices[i]-min:left[i-1]; } int max=prices[len-1]; for(int i=len-2;i>=0;i--) { max=prices[i]>max?prices[i]:max; right[i]=max-prices[i]>right[i]?max-prices[i]:right[i+1]; } int res=0; for(int i=0;i<len;i++) res=res>(left[i]+right[i])?res:(left[i]+right[i]); return res; } };