# 最大子序和
给定一个整数数组 nums
,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例 1:
输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
输出:6
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
示例 2:
输入:nums = [1]
输出:1
示例 3:
输入:nums = [0]
输出:0
示例 4:
输入:nums = [-1]
输出:-1
示例 5:
输入:nums = [-100000]
输出:-100000
提示:
1 <= nums.length <= 3 * 104
-105 <= nums[i] <= 105
进阶:如果你已经实现复杂度为 O(n)
的解法,尝试使用更为精妙的 分治法 求解。
以下错误的选项是?
## aop
### before
```cpp
#include
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
vector nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int res;
res = sol.maxSubArray(nums);
cout << res;
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
int maxSubArray(vector &nums)
{
if (nums.empty())
return 0;
int pre = 0, res = nums[0];
for (auto c : nums)
{
pre = max(pre, c);
res = max(pre, res);
}
return res;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
int maxSubArray(vector &nums)
{
int sum = 0, max_sum = INT_MIN;
for (int i = 0; i < nums.size(); i++)
{
if (sum < 0)
{
sum = nums[i];
}
else
{
sum += nums[i];
}
max_sum = max(sum, max_sum);
}
return max_sum;
}
};
```
### B
```cpp
class Solution
{
public:
int maxSubArray(vector &nums)
{
if (nums.size() == 0)
return NULL;
return fenzhifa(nums, 0, nums.size() - 1);
}
int fenzhifa(vector &nums, int left, int right)
{
if (left > right)
return INT_MIN;
if (left == right)
return nums[left];
int mid = (left + right) / 2;
int l = fenzhifa(nums, 0, mid - 1);
int r = fenzhifa(nums, mid + 1, right);
int t = nums[mid];
int max_num = nums[mid];
for (int i = mid - 1; i >= left; i--)
{
t += nums[i];
max_num = max(max_num, t);
}
t = max_num;
for (int i = mid + 1; i <= right; i++)
{
t += nums[i];
max_num = max(max_num, t);
}
return max(max(r, l), max_num);
}
};
```
### C
```cpp
class Solution
{
public:
int maxSubArray(vector &nums)
{
int maxsum = nums[0];
for (int i = 0; i < nums.size(); i++)
{
int sum = 0;
for (int j = i; j < nums.size(); j++)
{
sum = sum + nums[j];
if (maxsum < sum)
maxsum = sum;
}
}
return maxsum;
}
};
```