152.Maximum Product Subarray

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)

if the current value is negative, we have to swap local maximum value and minimum value.

class Solution {
    public int maxProduct(int[] nums) {
        int result = nums[0], localMax = nums[0], localMin = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] < 0) {
                int temp = localMax;
                localMax = localMin;
                localMin = temp;
            }
            localMax = Math.max(nums[i], localMax*nums[i]);
            localMin = Math.min(nums[i], localMin*nums[i]);
            result = Math.max(result, localMax);
        }
        return result;
    }
}

results matching ""

    No results matching ""