最大连续子数组
53. 最大子序和 - 力扣(LeetCode) (leetcode-cn.com)
我的做法,用前缀和
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int * presum = new int[nums.size()];
for (int i = 0; i < nums.size(); i++)
presum[i] = nums.at(i) + (i == 0 ? 0 :presum[i - 1]);
int min = 0;
int max = presum[0];
for (int i = 0; i < nums.size(); i++)
{
if (presum[i] - min > max)
max = presum[i] - min;
if (presum[i] < min)
min = presum[i];
}
delete []presum;
return max;
}
};
官方题解
动态规划
pre = max(pre+x, x);
maxAns = max(maxAns, pre);
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int maxAns = nums.at(0);
int pre = 0;
for (int x : nums)
{
pre = max(pre + x, x);
maxAns = max(maxAns, pre);
}
return maxAns;
}
};