Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array[2,3,-2,4],
The contiguous subarray[2,3]Has the largest Product =6.
Solution:
The main point of this question is not only to maintain a local maximum value, but also to maintain a local minimum value.
This question is similar to the maximum subarray model and the idea. It is still the "local optimization and global optimization" method in one-dimensional dynamic planning ". The difference here is that maintaining a local optimum is not enough to obtain the Global Optimum. This is because the multiplication is not as good as addition, and the accumulation result must increase progressively as long as it is positive, multiplication may be a negative number that seems to be small now, and then multiply it with another negative number to get the maximum product. But in fact, there is no much trouble. We only need to maintain a local maximum while maintaining a local minimum, so if the next element encounters a negative number, it is possible to obtain the Product Sum of the current maximum by multiplying the minimum value, which is also obtained by multiplication.
1 public class Main { 2 3 public static void main(String[] args) { 4 Main so = new Main(); 5 int[] A = { 2, 1, -2, 4 }; 6 System.out.println(so.maxProduct(A)); 7 } 8 9 public int maxProduct(int[] A) {10 if (A == null || A.length == 0)11 return 0;12 if (A.length == 1)13 return A[0];14 int max_local = A[0];15 int min_local = A[0];16 int global = A[0];17 for (int i = 1; i < A.length; ++i) {18 int max_copy = max_local;19 // max_local = Math.max(A[i] * max_copy, A[i] * min_local);20 // min_local = Math.min(A[i] * max_copy, A[i] * min_local);21 max_local=Math.max(Math.max(A[i], A[i]*max_copy), A[i]*min_local);22 min_local=Math.min(Math.min(A[i], A[i]*max_copy), A[i]*min_local);23 global = Math.max(max_local, global);24 }25 return global;26 }27 }
Note that when comparing (A [I]) (a [I] * max_copy) and (A [I] * min_local) in order to achieve the best local effect.
[Leetcode] Maximum Product subarray