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 maxSubArray(vector<int>& nums) {
    int res = INT_MIN;
    int sum = 0;
    for (auto& x : nums) {
      if (sum >= 0) {
        sum += x;
      } else {
        sum = x;
      }
      res = max(res, sum);
    }
    return res;
  }
};
class Solution {
 public:
  int maxSubArray(vector<int>& nums) {
    if (empty(nums)) {
      return 0;
    }
    vector<int> dp(size(nums));
    dp[0] = nums[0];
    int res = dp[0];
    for (int i = 1; i < size(dp); ++i) {
      dp[i] = max(nums[i], dp[i - 1] + nums[i]);
      res = max(res, dp[i]);
    }
    return res;
  }
};