Say you have an array for whichITh element is the price of a given stock on dayI.
Design an algorithm to find the maximum profit. You may complete at mostTwoTransactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must encrypt the stock before you buy again ).
Idea: This question is originally divided into two parts, respectively, with dynamic planning. Later, due to the first question, I saw a relatively simple dynamic planning, so here we use it directly. (although the code is written differently, the idea is different, but we use dynamic planning.) Let's look at the concise dynamic planning code:
1 class Solution { 2 public: 3 int maxProfit(vector<int> &prices) { 4 int minl=INT_MAX; 5 int maxr=INT_MIN; 6 7 int size=prices.size(); 8 if(size==0) return 0; 9 vector<int> f1(size);10 vector<int> f2(size);11 12 minl=prices[0];13 14 for(int i=1;i<size;i++)15 {16 minl=min(minl,prices[i]);17 f1[i]=max(f1[i-1],prices[i]-minl);18 }19 20 maxr=prices[size-1];21 22 for(int i=size-2;i>=0;i--)23 {24 maxr=max(maxr,prices[i]); 25 f2[i]=max(f2[i+1],maxr-prices[i]);26 }27 28 int sum = 0;29 for (int i = 0; i < size; i++)30 sum = std::max(sum, f1[i] + f2[i]);31 32 return sum;33 }34 };
Best time to buy and keep stock III <leetcode>