Problem: Maximum Product Subarray

ANKUSH KUMARANKUSH KUMAR
1 min read

Given an integer array nums, find a

subarray

the product

The test cases are generated so that the answer will fit in a 32-bit integer.

Example 1:

Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

Constraints:

  • 1 <= nums.length <= 2 * 10<sup>4</sup>

  • -10 <= nums[i] <= 10

  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

class Solution {
    public int maxProduct(int[] nums) {

        int max = nums[0], min = nums[0], ans = nums[0];
        int n = nums.length;

        for (int i = 1; i < n; i++) {

            // Swapping min and max
            if (nums[i] < 0){
                int temp = max;
                max = min;
                min = temp;
            }



            max = Math.max(nums[i], max * nums[i]);
            min = Math.min(nums[i], min * nums[i]);


            ans = Math.max(ans, max);
        }

        return ans;

    }
}
0
Subscribe to my newsletter

Read articles from ANKUSH KUMAR directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ANKUSH KUMAR
ANKUSH KUMAR

({MERN Stack Developer at mackph}) | <Ex-Internshala Student Partner(ISP 16)> | <5 star coder at Hackerrank> | <Self employed at Mackph> | <GSSoC '22 Contributor> | <Ex-Campus Ambassador at International MUN>