Maximum Product Subarray

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

public class Solution {
    public int maxProduct(int[] nums) {
        if (nums.length == 1) return nums[0];
        int max = 1, min = 1, res = nums[0];
        for (int num : nums) {
            int product1 = max * num, product2 = min * num;
            max = Math.max(Math.max(product1, product2), num);
            min = Math.min(Math.min(product1, product2), num);
            res = Math.max(max, res);
        }
        return res;
    }
}

Analysis

This problem is kind of like a lower DP problem
We loop through all the number from given input nums
To get the maximum product from contiguous subarray, we get the two products first
Then we update our max and min compared to the current num
At the end, we update our res with max of res and max
The reason why we have min is that two negative min can produces a max

results matching ""

    No results matching ""