Maximum Product of Three Numbers - Problem

Given an integer array nums, you need to find three numbers whose product is the maximum possible and return this maximum product.

The array can contain both positive and negative integers, which makes this problem more interesting than it first appears! Consider that the product of two negative numbers is positive, so the maximum product might not always come from the three largest numbers.

Example: In array [1, 2, 3, 4], the maximum product is 2 × 3 × 4 = 24. But in array [-4, -3, -2, -1, 60], the maximum product is (-4) × (-3) × 60 = 720!

Your task is to efficiently find and return the maximum possible product of any three numbers from the array.

Input & Output

example_1.py — Basic Positive Numbers
$ Input: [1, 2, 3]
Output: 6
💡 Note: The array has exactly three numbers, so we multiply all of them: 1 × 2 × 3 = 6.
example_2.py — Mixed Positive Numbers
$ Input: [1, 2, 3, 4]
Output: 24
💡 Note: The maximum product comes from the three largest numbers: 2 × 3 × 4 = 24. Using 1 would give a smaller product.
example_3.py — Negative Numbers Present
$ Input: [-1, -2, -3, 4]
Output: 24
💡 Note: Two negative numbers multiply to make a positive: (-2) × (-3) × 4 = 6 × 4 = 24. This is better than (-1) × (-2) × (-3) = -6.

Visualization

Tap to expand
Investment Portfolio StrategyArray: [-10, -5, 2, 4, 6] → Sorted: [-10, -5, 2, 4, 6]-10-5246Strategy 1: ConservativeTake 3 best: 2 × 4 × 6Result: 48Safe but might not be optimalStrategy 2: Risk Mitigation2 worst + 1 best: (-10) × (-5) × 6Result: 300Negatives cancel out!🏆 Winner: Strategy 2Maximum Product: 300
Understanding the Visualization
1
Sort the Portfolio
Arrange all investments from worst to best performance
2
Identify Key Players
Focus on the 2 worst performers and 3 best performers
3
Strategy 1: Play It Safe
Choose the 3 best performing investments
4
Strategy 2: Risk Mitigation
Use 2 worst performers (they cancel out) + 1 best performer
5
Choose the Winner
Compare both strategies and pick the one with maximum return
Key Takeaway
🎯 Key Insight: The maximum product of three numbers comes from either the three largest values OR two smallest values (if negative) times the largest value. Sorting helps us quickly identify these candidates!

Time & Space Complexity

Time Complexity
⏱️
O(n log n)

Dominated by the sorting step, comparison is O(1)

n
2n
Linearithmic
Space Complexity
O(1)

Only using constant extra space for calculations (assuming in-place sort)

n
2n
Linear Space

Constraints

  • 3 ≤ nums.length ≤ 104
  • -1000 ≤ nums[i] ≤ 1000
  • The array will always have at least 3 elements
Asked in
Amazon 45 Microsoft 38 Google 32 Apple 28
35.0K Views
Medium-High Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen