题目:
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
.
思路:
保存两个值max和leftSum,max就是到目前为止所能得到的最大值,leftSum为包含当前元素的最大子串之和。然后从左往右扫,下面的代码的if else语句把各种情况都摆明了。
package array; public class MaximumSubarray { public int maxSubArray(int[] nums) { int n; if (nums == null || (n = nums.length) == 0) return 0; int max = nums[0]; int leftSum = nums[0]; for (int i = 1; i < n; ++i) { if (nums[i] >= 0) { if (leftSum >= 0) { leftSum += nums[i]; } else { leftSum = nums[i]; } if (max < leftSum) max = leftSum; } else { if (leftSum + nums[i] >= 0) { leftSum += nums[i]; } else { leftSum = nums[i]; } if (max < leftSum) max = leftSum; } } return max; } public static void main(String[] args) { // TODO Auto-generated method stub int[] nums = { /*-2,1,-3,4,-1,2,1,-5,4*/ -2, -1 }; MaximumSubarray m = new MaximumSubarray(); System.out.println(m.maxSubArray(nums)); } }
这个代码可以合并,如下:
package array; public class MaximumSubarray { public int maxSubArray(int[] nums) { int n; if (nums == null || (n = nums.length) == 0) return 0; int max = nums[0]; int leftSum = nums[0]; for (int i = 1; i < n; ++i) { if (leftSum >= 0 && leftSum + nums[i] >= 0) { leftSum += nums[i]; } else { leftSum = nums[i]; } if (max < leftSum) max = leftSum; } return max; } public static void main(String[] args) { // TODO Auto-generated method stub int[] nums = { -2, -1 }; MaximumSubarray m = new MaximumSubarray(); System.out.println(m.maxSubArray(nums)); } }