LeetCode:53. Maximum Subarray
1 package day20170206; 2 //LeetCode:53. Maximum Subarray 3 /* 4 Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 5 6 For example, given the array [-2,1,-3,4,-1,2,1,-5,4], 7 the contiguous subarray [4,-1,2,1] has the largest sum = 6. 8 9 click to show more practice. 10 11 More practice: 12 If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 13 */ 14 public class maxSubArray53 { 15 public static int maxSubArray(int[] nums) { 16 int max=nums[0]; 17 for(int i=0;i<nums.length;i++){ 18 for(int j=i,sum=0;j<nums.length;j++){ 19 sum+=nums[j]; 20 if(sum>max) 21 max=sum; 22 } 23 } 24 return max; 25 } 26 //study if(AB+C)<C,AB<0,且A<AB 27 public static int maxSubArray2(int[] nums){ 28 int max=nums[0],subMax=nums[0]; 29 for(int i=1;i<nums.length;i++){ 30 subMax=Math.max(nums[i]+subMax, nums[i]); 31 max=Math.max(max, subMax); 32 } 33 return max; 34 } 35 public static void main(String[] args) { 36 // TODO Auto-generated method stub 37 int[] nums={-2,1,-3,4,-1,2,1,-5,4}; 38 int[] nums2={-2,1}; 39 int[] nums3={1}; 40 41 System.out.println(maxSubArray(nums)); 42 System.out.println(maxSubArray(nums2)); 43 System.out.println(maxSubArray(nums3)); 44 45 System.out.println(maxSubArray2(nums)); 46 System.out.println(maxSubArray2(nums2)); 47 System.out.println(maxSubArray2(nums3)); 48 } 49 50 }