leetcode-----53. 最大子序和
算法1(前缀和暴力法)
时间复杂度:\(O(n^2)\)
代码
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int res = INT_MIN, sum = 0;
for (int i = 0; i < nums.size(); ++i) {
sum = 0;
for (int j = i; j < nums.size(); ++j) {
sum += nums[j];
res = max(res, sum);
}
}
return res;
}
};
算法2(前缀和优化)
时间复杂度:\(O(n)\)
代码
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int res = nums[0], sum = 0, min_sum = 0;
for (auto x: nums) {
sum += x;
res = max(res, sum - min_sum);
min_sum = min(min_sum, sum);
}
return res;
}
};
算法3(归并法)
时间复杂度:\(O(nlogn)\)
代码
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if (nums.size() == 0) return 0;
return help(nums, 0, nums.size() -1);
}
int help(vector<int> nums, int l, int r) {
if (l > r) return INT_MIN;
int mid = (l + r) >> 1;
int left = help(nums, l, mid - 1);
int right = help(nums, mid + 1, r);
int l_sum = 0;
int sum = 0;
for (int i = mid - 1; i >= l; --i) {
sum += nums[i];
l_sum = max(l_sum, sum);
}
int r_sum = 0;
sum = 0;
for (int i = mid + 1; i <= r; ++i) {
sum += nums[i];
r_sum = max(sum, r_sum);
}
return max(l_sum + r_sum + nums[mid], max(left, right));
}
};
算法4
时间复杂度:\(O(n)\)
代码
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum = nums[0], ans = nums[0];
for (int i = 1; i < nums.size(); ++i) {
if (sum < 0) sum = nums[i];
else sum += nums[i];
ans = max(ans, sum);
}
return ans;
}
};