Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
一道很有趣的Easy题目,一开始用暴力算法,果然只比5%的解法快。。。。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int len = nums.size();
int sum,max_sum;
max_sum = INT_MIN;
for(int i=0;i<len;i++)
{
int sum = 0;
for(int j=i;j<len;j++)
{
sum += nums[j];
if(sum > max_sum) max_sum = sum;
}
}
return max_sum;
}
};
去评论区参考了一下更优解,果然颜值就是战斗力,简洁美观的代码效果一般都很不错。。。
for循环中头两句比较清楚明白,最后一句是关键,它可以自动抛弃和为负数的部分。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int len = nums.size();
int sum,max_sum;
max_sum = INT_MIN;
sum = 0;
for(int i=0;i<len;i++)
{
sum += nums[i];
max_sum = max(max_sum, sum);
sum = max(sum,0);
}
return max_sum;
}
};