LeetCode -- Maximum Subarray
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, 1, −5, 4],
The contiguous subarray[4, −1, 1]Has the largest sum =6.
Question: Find the continuous and maximum number in the integer array.
Start from scratch. If there are any and less than 0, ignore the preceding sum and calculate ahead.
Public static int maxSubArray (int [] A) {int sum = 0; int maxSum = Integer. MIN_VALUE; for (int I = 0; I <. length; I ++) {sum + = A [I]; if (sum <0) sum = 0; maxSum = Math. max (maxSum, sum);} return maxSum ;}
Dynamic Planning Method.
Public static int maxSubArray (int [] A) {int max = A [0]; int sum [] = new int [. length]; sum [0] = A [0]; for (int I = 1; I <. length; I ++) {sum [I] = Math. max (A [I], sum [I-1] + A [I]); max = Math. max (max, sum [I]);} return max ;}