Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
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;
}
};
dp[i]
表示以 nums[i]
为子数组尾元素时的最大和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;
}
};