Leetcode-Maximum Product Subarray(Java)

Question:

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.

Thinking:

This problem is similiar with the MaxSubArray. One thing we need to notice is that we should maintian another variable which is the minimum value of the negative value. When it multiple the negtive value in the array, it maybe the maximum.

Solution:

public int maxProduct(int[] nums) {
    int l = nums.length;
    int max = nums[0];
    int maxhere = nums[0];
    int minhere = nums[0];

    for (int i = 1; i < l; i++) {
        if (nums[i] >= 0) {
            maxhere = Math.max(maxhere*nums[i], nums[i]);
            minhere = Math.min(minhere*nums[i], nums[i]);
        } else {
            int temp = maxhere;
            maxhere = Math.max(minhere*nums[i], nums[i]);
            minhere = Math.min(temp*nums[i], nums[i]);
        }
        max = Math.max(maxhere, max);
    }

    return max;