Maximum Product Subarray LeetCode Solution | Easy Approach

Minimum Cost to Merge Stones
Share:

Maximum Product Subarray Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.

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

subarray is a contiguous subsequence of the array.

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 * 104
  • -10 <= nums[i] <= 10
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

Maximum Product Subarray Solutions

Time: O(n)
Space: O(1)

C++

class Solution {
 public:
  int maxProduct(vector<int>& nums) {
    int ans = nums[0];
    int dpMin = nums[0];  // min so far
    int dpMax = nums[0];  // max so far

    for (int i = 1; i < nums.size(); ++i) {
      const int num = nums[i];
      const int prevMin = dpMin;  // dpMin[i - 1]
      const int prevMax = dpMax;  // dpMax[i - 1]
      if (num < 0) {
        dpMin = min(prevMax * num, num);
        dpMax = max(prevMin * num, num);
      } else {
        dpMin = min(prevMin * num, num);
        dpMax = max(prevMax * num, num);
      }
      ans = max(ans, dpMax);
    }

    return ans;
  }
};

Java

 class Solution {
  public int maxProduct(int[] nums) {
    int ans = nums[0];
    int dpMin = nums[0]; // min so far
    int dpMax = nums[0]; // max so far

    for (int i = 1; i < nums.length; ++i) {
      final int num = nums[i];
      final int prevMin = dpMin; // dpMin[i - 1]
      final int prevMax = dpMax; // dpMax[i - 1]
      if (num < 0) {
        dpMin = Math.min(prevMax * num, num);
        dpMax = Math.max(prevMin * num, num);
      } else {
        dpMin = Math.min(prevMin * num, num);
        dpMax = Math.max(prevMax * num, num);
      }
      ans = Math.max(ans, dpMax);
    }

    return ans;
  }
}

Python


class Solution:
  def maxProduct(self, nums: List[int]) -> int:
    ans = nums[0]
    prevMin = nums[0]
    prevMax = nums[0]

    for i in range(1, len(nums)):
      mini = prevMin * nums[i]
      maxi = prevMax * nums[i]
      prevMin = min(nums[i], mini, maxi)
      prevMax = max(nums[i], mini, maxi)
      ans = max(ans, prevMax)

    return ans

Watch Tutorial

Checkout more Solutions here

Leave a Comment

Your email address will not be published. Required fields are marked *

x