For example, given the array
[2,3,-2,4]
,the contiguous subarray
[2,3]
has the largest product = 6
.
public class Solution { public int maxProduct(int[] A) { // Similar to "Maximum Subarray" but more complicated. int n = A.length; if (n == 0) return 0; if (n == 1) return A[0]; // Note: currentMin*A[i] may become currentMax (neg*neg = positive) // Simiarly, currentMax*A[i] may become currentMin int currentMax = A[0]; int currentMin = A[0]; int max = A[0]; for (int i = 1; i < n; i++) { int previousMax = currentMax; currentMax = Math.max(Math.max(currentMax*A[i], A[i]), currentMin*A[i]); currentMin = Math.min(Math.min(currentMin*A[i], A[i]), previousMax*A[i]); max = Math.max(max, currentMax); } return max; } }
No comments:
Post a Comment