MEDIUM NC#107 Blind #6 Dynamic Programming 1D

152. Maximum Product Subarray

šŸ“– Problem

Given an integer array nums, find the subarray that has the largest product and return that product.

🧠 Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • •Array methods (`push`, `pop`, `shift`, `slice`)
  • •Object/Map/Set usage patterns
  • •Function parameter and return typing
  • •Array DP table updates
  • •State transition thinking
  • •Base case initialization

Logical Thinking Concepts

  • •Define invariants before coding
  • •Check edge cases first (`[]`, single element, duplicates)
  • •Estimate time/space before implementation
  • •Apply Dynamic Programming reasoning pattern

šŸ’” Approach

  • → Track both max and min at each position (negative * negative = positive)
  • → For each number: newMax = max(num, max*num, min*num)
  • → newMin = min(num, max*num, min*num)
  • → Time: O(n), Space: O(1)

šŸ› ļø Hints & Pitfalls

Hints

  • •Track both max and min at each position (negative * negative = positive)
  • •For each number: newMax = max(num, max*num, min*num)
  • •newMin = min(num, max*num, min*num)

Common Pitfalls

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

🧪 Test Cases

Hidden tests on submit: 2

Test Case 1
Not run
Input:
maxProduct([2,3,-2,4]);
Expected:
6
Test Case 2
Not run
Input:
maxProduct([-2,0,-1]);
Expected:
0
Test Case 3
Not run
Input:
maxProduct([-2,3,-4]);
Expected:
24

šŸ“ Code Editor

šŸ“š Reference Solution

ā–¼
⌘K Search āŒ˜ā†© Run ⌘S Submit