1 暴力法
时间复杂度: O ( n 2 ) O(n^2) O(n2)
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int maxSum = INT_MIN;
for (int i = 0; i < nums.size(); i++) {
int sum = 0;
int curSum = INT_MIN;
for (int j = i; j < nums.size(); j++) {
sum += nums[j];
curSum = max(curSum, sum);
}
maxSum = max(maxSum, curSum);
}
return maxSum;
}
};
2 区间贪心算法
时间复杂度: O ( n ) O(n) O(n)
局部最优
:当前和为负数时立即停止加和,因为前面的负数和只会拉低后面的和(全负数案例 )
全局最优
:选取最大“连续和”
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int maxSum = INT_MIN;
int curSum = 0; // 当前区间中的和
for (int i = 0; i < nums.size(); i++) {
curSum += nums[i];
maxSum = max(maxSum, curSum);
// 核心:若之前的curSum为负数, 则置0, 因为前面的负数和一定会拉低后面的正和(全负数也满足)
curSum = max(curSum, 0); // 修正最大和的起始位置
}
return maxSum;
}
};
3 动态规划
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int size = nums.size();
int preSum = nums[0], curSum = 0;
int maxSum = nums[0];
for (int i = 1; i < size; i++) {
curSum = max(nums[i], nums[i] + preSum);
preSum = curSum;
maxSum = max(maxSum, curSum);
}
return maxSum;
}
};