class Solution { /** * 分治 * @param nums * @param l * @param r * @return */ private int getMaxWithDivision(int[] nums, int l, int r) { if (l == r) { return nums[l]; } int m = (l + r) >>> 1; int left = getMaxWithDivision(nums, l, m); int right = getMaxWithDivision(nums, m + 1, r); int lSum = 0; int lMax = nums[m]; for (int i = m;i >= l; -- i) { lSum += nums[i]; lMax = Math.max(lMax, lSum); } int rSum = 0; int rMax = nums[m + 1]; for (int i = m + 1; i <= r; ++ i) { rSum += nums[i]; rMax = Math.max(rMax, rSum); } return Math.max(Math.max(left, right), lMax + rMax); } /** * dp * @param nums * @return */ private int getMaxWithDp(int[] nums) { int sum = 0; int max = nums[0]; for (int i = 0;i < nums.length;++ i) { sum += nums[i]; max = Math.max(sum, max); if (sum < 0) { sum = 0; } } return max; } public int maxSubArray(int[] nums) { if (nums == null || nums.length == 0) { return 0; } return getMaxWithDp(nums); } }
转载于:https://blog.51cto.com/tianyiya/2172773