Assume dp[i][0] represents the maximum profit on day i without holding stock, dp[i][1] represents the maximum profit on day i while holding stock Then:
dp[i][0]=max(dp[i−1][0],dp[i−1][1]+prices[i])
Not holding stock on day i could be because we didn’t hold yesterday and didn’t buy today, or we held yesterday and sold today (here we directly add prices[i] because when buying stock we directly subtract prices[i]; we can understand it as maintaining the current balance)
dp[i][1]=max(dp[i−1][0]−prices[i],dp[i−1][1])
Holding stock on day i could be because we held yesterday and didn’t buy today, or we held yesterday and bought today (here we directly subtract prices[i] because when buying stock we directly add prices[i]; we can understand it as maintaining the current balance)
classSolution { public: intmaxProfit(vector<int> &prices){ // dp[i][0] maximum profit on day i without holding stock // dp[i][1] maximum profit on day i while holding stock int n; n = prices.size(); vector<pair<int, int>> dp(n, {0, 0}); // dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i]) // dp[i][1] = max(dp[i-1][0]-prices[i], dp[i-1][1]) dp[0].first = 0; dp[0].second = -prices[0];