53. Maximum Subarray
题目:Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4]
,
the contiguous subarray [4,-1,2,1]
has the largest sum = 6
.
题目意思:给一个数组,找出最大的子数组,返回子数组的和。
思路:遍历数组,设置两个参数,max返回最大值,sum存储数组和。如果sum小于数组元素,则将sum储存该元素,并且让max跟该元素相比较,max小于该元素则修改其值。每次遍历都让max跟sum比较,max存储较大值。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum = 0;
if(nums.size() <= 0){
return sum;
}
int max = nums[0];
for(int i = 0;i < nums.size();i++){
sum += nums[i];
if(max < sum){
max = sum;
}
if(sum < nums[i]){
sum = nums[i];
if(max < nums[i]){
max = nums[i];
}
continue;
}
}
return max;
}
};