问题描述:
ind 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
.
public class MaxSubarray { public int maxSubArray(int[] nums) { int sum = nums[0]; int max = nums[0]; for(int i = 1; i < nums.length; i ++) { if(sum < 0) { sum = 0; } sum += nums[i]; if(max < sum) { max = sum; } } return max; } //穷举法O(n^3) public int maxSubArray1(int[] nums) { int max = 0; for(int i = 0; i < nums.length; i ++) { for(int j = i; j < nums.length; j ++) { int sum = 0; for(int k = i; k < j; k ++) { sum += nums[k]; } if(sum > max) { max = sum; } } } return max; } //O(n^2) public int maxSubArray2(int[] nums) { int max = 0; for(int i = 0; i < nums.length; i ++) { int sum = 0; for(int j = i; j < nums.length; j ++) { sum += nums[j]; if(sum > max) { max = sum; } } } return max; } }