Skip to content

Latest commit

 

History

History
73 lines (56 loc) · 2.61 KB

152.md

File metadata and controls

73 lines (56 loc) · 2.61 KB

LeetCode #152: Maximum Product Subarray

🔗 Problem Link: Maximum Product Subarray

Problem Statement 🟡 Difficulty: Medium

Given an integer array nums, find a contiguous subarray 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.

🔹 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 subarray of nums is guaranteed to fit in a 32-bit integer.

Solution Explanation

Brute Force Approach (O(n²))

A naive approach would be to iterate through all possible subarrays and compute their product.

  • Start at each index and multiply it with the next elements, keeping track of the maximum product.
  • This results in a time complexity of O(n²), which is inefficient for large inputs.

Optimized Approach (O(n))

To improve efficiency, we use a dynamic tracking method to handle both positive and negative numbers effectively.

🔹 Key Observations

  1. Tracking Maximum & Minimum Products

    • Since multiplying a negative number with a small (negative) product can make it large, we track both the maximum (curmax) and minimum (curmin) products at each step.
    • For each number, we calculate:
      curmax = max(n * curmax, n * curmin, n)
      curmin = min(temp, n * curmin, n)
    • This ensures we correctly handle cases where negatives flip signs.
  2. Handling Zeroes

    • If 0 is encountered, multiplying further would result in zero.
    • To prevent curmax and curmin from being permanently affected, we reset them to 1 whenever a 0 appears.

Time Complexity: O(n)

Since we traverse the array only once, the solution runs in linear time, making it highly efficient.


Example Dry Run

Example: nums = [2,3,-2,4]

Step n curmax curmin res
1st Iteration 2 2 2 2
2nd Iteration 3 6 3 6
3rd Iteration -2 -2 -12 6
4th Iteration 4 4 -48 6

Final Output: 6


This approach ensures we efficiently find the maximum product subarray in just O(n) time complexity. 🚀