分治:
暴力最大子序列:
public static int maxSubarray(int[] nums) {if (nums == null || nums.length == 0) {return 0;}int max = Integer.MIN_VALUE;for (int begin = 0; begin < nums.length; begin++) {for (int end = begin; end < nums.length; end++) {//sum是子序列的和int sum = 0;for (int i = begin; i <= end; i++) {sum += nums[i];}max = Math.max(max, sum);}}return max;}
分治2: 暴力优化2:
public static int maxSubarray2(int[] nums) {if (nums == null || nums.length == 0) {return 0;}int max = Integer.MIN_VALUE;for (int begin = 0; begin < nums.length; begin++) {int sum = 0;for (int end = begin; end < nums.length; end++) {//sum是子序列的和sum += nums[end];max = Math.max(max, sum);}}return max;}
分治:
public static int divideAndConquer(int[] nums) {if (nums == null || nums.length == 0) {return 0;}return divideAndConquer(nums, 0, nums.length);}/*** 求出begin到end中最大子序列的和*/public static int divideAndConquer(int[] nums, int begin, int end) {if (end - begin < 2) {return nums[begin];}int mid = (begin + end) >> 1;int leftMax = Integer.MIN_VALUE;int leftSum = 0;int rightMax = Integer.MIN_VALUE;int rightSum = 0;for (int i = mid - 1; i >= begin; i--) {leftSum += nums[i];leftMax = Math.max(leftMax, leftSum);}for (int i = mid; i < end; i++) {rightSum += nums[i];rightMax = Math.max(rightMax, rightSum);}int max = leftMax + rightMax;return Math.max(max, Math.max(divideAndConquer(nums, begin, mid), divideAndConquer(nums, mid, end)));}
