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
.
1 int maxSubArray(int* nums, int numsSize) { 2 int sum = 0; 3 int sum_max = INT_MIN; 4 int i; 5 for(i = 0; i < numsSize; i++) 6 { 7 if(sum < 0) //如果sum小於0 ,就捨棄 8 sum = 0; 9 sum += nums[i]; 10 if(sum > sum_max) 11 sum_max = sum; 12 } 13 return sum_max; 14 }