1. Title
Maximum Subarray
2. Http address
https://leetcode.com/problems/maximum-subarray/
3. The question
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4]
,
the contiguous subarray [4,−1,2,1]
has the largest sum = 6
.
4 My code(AC)
1 public int maxSubArray(int[] nums) { 2 3 if ( nums == null || nums.length == 0) 4 return 0; 5 int contiguousMax[] = new int[nums.length]; 6 contiguousMax[0] = nums[0]; 7 for(int i = 1 ; i < nums.length; i++) 8 { 9 contiguousMax[i] = Math.max(contiguousMax[i-1] + nums[i], nums[i]); 10 } 11 int opt_cur = nums[0]; 12 for(int i = 1; i < nums.length; i++) 13 { 14 opt_cur = Math.max(opt_cur, contiguousMax[i]); 15 } 16 return opt_cur; 17 } 18 19 // Accepted 20 public int maxSubArrayTwo(int[] nums) { 21 22 if ( nums == null || nums.length == 0) 23 return 0; 24 25 int opt_cur = nums[0]; 26 int contiguousMax = nums[0]; 27 for(int i = 1; i < nums.length; i++) 28 { 29 contiguousMax = Math.max(contiguousMax + nums[i], nums[i]); 30 opt_cur = Math.max(opt_cur, contiguousMax); 31 } 32 return opt_cur; 33 }