LinkedIn FAQ-maximum sum/product subarray
Maximum Sum subarray is the original question of leetcode, which is almost identical to the idea of gas station. The conclusions used in the answers must be proved in mathematics.
123456789101112 |
public int maxSubArray( int [] A) { int sum = 0 ; int max = Integer.MIN_VALUE; for ( int i = 0 ; i < A.length; i++) { sum += A[i]; if (sum > max) max = sum; if (sum < 0 ) sum = 0 ; } return max; } |
Maximum Product subarray actually only needs to constantly record two values, Max and Min. Max is the largest positive product so far, Min is the smallest negative product so far, or 1.
123456789101112131415161718192021 |
public int maxProduct( int [] A) { int x = 1 ; int max = 1 ; int min = 1 ; for ( int i = 0 ; i < A.length; i++) { if (A[i] == 0 ) { max = 1 ; min = 1 ; } else if (A[i] > 0 ) { max = max * A[i]; min = Math.min(min * A[i], 1 ); } else { int temp = max; max = Math.max(min * A[i], 1 ); min = temp * A[i]; } if (max > x) x = max; } return x; } |
Http://shepherdyuan.wordpress.com/2014/07/23/linkedin-maximum-sumproduct-subarray/
Leetcode-Maximum Product subarray ZZ