标签:
dp的方法比较简单就不写了。这里用分治法,对与一个数组,最大的子区间可以在left 到 mid这一段, 也可能划过mid, 也可能在mid 到 right, 所以分别求这三段,取最大的结果。求左右段最大的时候才用分治的想法。算法复杂度为o(nlogn)
public class Solution { public int maxSubArray(int[] nums) { return helper(nums, 0, nums.length - 1); } public int helper(int[] nums, int left, int right) { if (left > right) { return 0; } if (left == right) { return nums[left]; } if (right - left == 1) { return Math.max(Math.max(nums[left], nums[left] + nums[right]), nums[right]); } int mid = left + (right - left) / 2; int mid_max = mid_max(nums, left, right); int left_max = helper(nums, left, mid - 1); int right_max = helper(nums, mid + 1, right); return Math.max(Math.max(mid_max, left_max), right_max); } public int mid_max(int[] nums, int left, int right) { int mid = (left + right) / 2; int left_max = Integer.MIN_VALUE; int right_max = Integer.MIN_VALUE; int l = 0; int r = 0; for (int i = mid - 1; i >= left; i --) { l += nums[i]; left_max = Math.max(l, left_max); } for (int i = mid + 1; i <= right; i++) { r += nums[i]; right_max = Math.max(r, right_max); } int[] arr = new int[]{left_max + right_max + nums[mid], nums[mid], nums[mid] + left_max, nums[mid] + right_max}; Arrays.sort(arr); return arr[3]; } }
标签:
原文地址:http://www.cnblogs.com/vision-love-programming/p/5018892.html