Leetcode: Maximum Product Subarray

来源:互联网 发布:量子蚁群算法程序 编辑:程序博客网 时间:2024/06/03 22:47

Problem:

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:

See some examples first.


public class Solution {    public int maxProduct(int[] A) {        if (A.length == 1) {            return A[0];        }        int result = A[0]; // must be assigned A[0] (but not Integer.VALUE_MIN) in case A[0] is the largest product.        int maxProduct = A[0]; // local maxProduct        int minProduct = A[0]; // local minProduct        for (int i = 1; i < A.length; i++) {            int tmp = maxProduct;            maxProduct = Math.max(Math.max(maxProduct * A[i], A[i]), minProduct * A[i]);            minProduct = Math.min(Math.min(tmp * A[i], A[i]), minProduct * A[i]);            if (maxProduct > result) {                result = maxProduct;            }        }        return result;    }}



0 0
原创粉丝点击