Advertisement
Guest User

Untitled

a guest
Dec 16th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.60 KB | None | 0 0
  1. int maxProfit(const vector<int>& prices) {
  2.         if (prices.empty()) return 0;
  3.         auto memo = vector<int>(prices.size(), -1);
  4.         memo.back() = 0;
  5.        
  6.         for (int i = prices.size() - 2; i >= 0; --i) {
  7.             int res = memo[i + 1]; // do not sell (and do not buy)
  8.             for (int j = i + 1; j < prices.size(); ++j) { // j is day to buy
  9.                 auto suffix_res = j + 2 < memo.size() ? memo[j + 2] : 0;
  10.                 res = max(res, prices[j] - prices[i] + suffix_res); // sell
  11.             }
  12.             memo[i] = res;
  13.         }
  14.        
  15.         return memo[0];
  16.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement