题目:
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.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
题意:
找出连续子串和的最大值,要求时间复杂度O(n)
思路:
时间复杂度O(n),故边遍历边筛选最大值。当前元素加不加入子串中主要是看当前元素的值和前面子串的和+当前元素值哪个更大;然后遍历一次就筛选一次
Code:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int i,n=nums.size(),ans=INT_MIN,sum=0;
for(i=0;i<n;i++){
sum=max(sum+nums[i],nums[i]);
ans=max(ans,sum);
}
return ans;
}
};