LeetCode 53 ,分治解
class Solution { public int maxSubArray(int[] nums) { if(nums == null || nums.length == 0) return 0; return maxSubArray(nums,0,nums.length-1); } private int maxSubArray(int[] nums,int L,int R) { if(L == R) return nums[L]; int mid = L+(R-L>>1); int left = maxSubArray(nums,L,mid); int right = maxSubArray(nums,mid+1,R); int middle = maxCsArray(nums,L,mid,R); if(left>=right&&left>=middle) return left; else if(right>=left&&right>=middle) return right; else return middle; } private int maxCsArray(int[] nums,int L,int mid,int R) { int leftSum = Integer.MIN_VALUE; int sum = 0; for(int i = mid;i>=L;i--) { sum+=nums[i]; if(sum > leftSum) leftSum = sum; } int rightSum = Integer.MIN_VALUE; sum = 0; for(int i = mid+1 ;i<=R;i++) { sum+=nums[i]; if(sum>rightSum) rightSum = sum; } return leftSum+rightSum; } }
借鉴部分,需要好好品味其中分治的精髓,虽然可以用其他较好方法