Maximum Product Subarray in an Array

Arrays FAQs(Hard) Hard
  • This problem is a classic example of dynamic programming, which is fundamentally used in various industry-level applications for optimizing solutions to complex problems
  • For instance, database software like Oracle and MySQL use similar concepts to optimize query parsing
  • Besides, algorithms similar to this are critical in financial technologies which rely on historical data to analyze trends or optimize investment portfolios
  • For instance, identifying the most lucrative series of transactions (which operates similarly to finding a subarray with the largest product) is a key strategy used in stock market analysis

Given an integer array nums. Find the subarray with the largest product, and return the product of the elements present in that subarray.


A subarray is a contiguous non-empty sequence of elements within an array.

Examples:

Input: nums = [4, 5, 3, 7, 1, 2]

Output: 840

Explanation: The largest product is given by the whole array itself

Input: nums = [-5, 0, -2]

Output: 0

Explanation: The largest product is achieved with the following subarrays [0], [-5, 0], [0, -2], [-5, 0, 2].

Input: nums = [1, -2, 3, 4, -4, -3]

Constraints

  • 1 <= nums.length <= 104
  • -10 <= nums[i] <= 10
  • -109 <= product of any prefix or suffix of nums <= 109

Hints

  • Instead of keeping just a maximum sum, maintain both the maximum product and minimum product at each step, since negative numbers can flip signs.
  • A negative number can make a large positive product negative, but it can also turn a large negative product positive if multiplied with another negative. Therefore, keep track of both the max product so far and the min product so far, swapping when needed.

Company Tags

Rakuten Intel Freshworks Red Hat Docker Chewy Zoho Visa HCL Technologies Unity Technologies JPMorgan Chase Bain & Company Zynga Wayfair Databricks Micron Technology PayPal Mastercard Stripe AMD NVIDIA IBM PwC Riot Games Siemens Healthineers Google Microsoft Amazon Meta Apple Netflix Adobe