Maximum Product Subarray

来源:互联网 发布:java内部类 编辑:程序博客网 时间:2024/06/06 17:38

Q:

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:

public class Solution {    public int maxProduct(int[] A) {        if(A.length == 1)            return A[0];        int min = A[0];        int max = A[0];        int globalMax = max;        for (int i = 1; i < A.length; i++) {            int copy = max;            max = Math.max(Math.max(A[i]*max, A[i]*min), A[i]);            min = Math.min(Math.min(A[i]*copy, A[i]*min), A[i]);            globalMax = Math.max(globalMax, max);        }        return globalMax;    }}


0 0
原创粉丝点击