Hone logo
Hone
Problems

Maximum Product Subarray

Given an array of integers, the goal is to find the contiguous subarray within the array that has the largest product. This is a fundamental problem in algorithm design, often encountered in interviews and competitive programming, as it tests your ability to handle dynamic programming and edge cases involving negative numbers.

Problem Description

You are given an array of integers, nums. Your task is to find the contiguous subarray within nums that has the largest product. A contiguous subarray is a sequence of elements that are adjacent in the original array.

Key Requirements:

  • The subarray must contain at least one number.
  • You need to return the maximum product achievable by any contiguous subarray.

Expected Behavior:

  • If the input array is empty, the behavior is undefined (or you can specify a default return value like 0 or an error). For this challenge, assume the input array will not be empty.
  • Consider cases with positive numbers, negative numbers, and zeros.

Edge Cases to Consider:

  • An array with only negative numbers.
  • An array containing zeros.
  • An array with a single element.

Examples

Example 1:

Input: [2, 3, -2, 4]
Output: 6
Explanation: The subarray [2, 3] has the largest product of 6.

Example 2:

Input: [-2, 0, -1]
Output: 0
Explanation: The subarray [0] has the largest product of 0. Note that [-2, -1] is not a subarray because it skips 0.

Example 3:

Input: [-2, 3, -4]
Output: 24
Explanation: The subarray [-2, 3, -4] has the largest product of 24.

Constraints

  • 1 <= nums.length <= 2 * 10^4
  • -10 <= nums[i] <= 10 (This means the individual numbers are within a small range, but their products can grow larger)
  • The product of any prefix or suffix of nums is guaranteed to fit within a standard 32-bit signed integer.

Notes

  • Remember that the product of two negative numbers is positive. This is a crucial observation for solving this problem.
  • You might need to keep track of not just the maximum product ending at a certain position, but also the minimum product, as a very small negative number multiplied by another negative number could result in a large positive product.
  • Consider what happens when you encounter a zero. A zero effectively "resets" the product calculation for subarrays that span across it.
Loading editor...
plaintext