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.
Subject to the effect:
Given the array, and found with the largest continuous sub-arrays, and returns the maximum.
Understanding:
Initial maximum and max, and the sum of temporary values nums [0].
When the sum <0, the next number if nums [i] is greater than the sum, the sum reset to nums [i].
When the sum> 0, the number of directly adding a next nums [i].
Always need to be the maximum sum and max comparison, update max value.
Code C ++:
class Solution { public: int maxSubArray(vector<int>& nums) { int n = nums.size(); if(n==0) return 0; int max = nums[0],sum=nums[0] ,i; for(i=1;i<n;++i){
if(sum<0 && sum<nums[i]){ sum = nums[i]; if(max<sum) max = sum; continue; } sum = sum + nums[i]; if(max<sum) max = sum; } if(max<sum) max = sum; return max; } };
operation result:
When executed with: 12
MS
memory consumption:
9.4 MB