41. Maximum Subarray
Description
Given an array of integers, find a contiguous subarray which has the largest sum.
The subarray should contain at least one number.
Example
Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1]
has the largest sum = 6.
Solution
public class Solution {
/**
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
public int maxSubArray(int[] nums) {
int MaxSum = nums[0], ThisSum = 0;
for(int i=0;i<nums.length;i++){
ThisSum += nums[i];
if(ThisSum > MaxSum){
MaxSum = ThisSum;
}else if(ThisSum < 0){
ThisSum = 0;
}
}
return MaxSum;
}
}