LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
class Solution {
 public:
  int maxProfit(vector<int>& prices) {
    int sz = size(prices);
    if (sz < 2) {
      return 0;
    }
    vector<int> hold(sz);  // 持仓
    vector<int> sold(sz);  // 空仓
    vector<int> cool(sz);  // 冷冻期
    hold[0] = -prices[0];
    for (int i = 1; i < sz; ++i) {
      hold[i] = max(hold[i - 1], sold[i - 1] - prices[i]);
      sold[i] = max(cool[i - 1], sold[i - 1]);
      cool[i] = hold[i - 1] + prices[i];
    }
    return max(cool[sz - 1], sold[sz - 1]);
  }
};