Maximum Product of Three Numbers - Problem

Given an integer array nums, find three numbers whose product is maximum and return the maximum product.

Note: The solution is guaranteed to fit in a 32-bit integer.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3]
Output: 6
💡 Note: Only one triplet possible: 1 × 2 × 3 = 6
Example 2 — Negative Numbers
$ Input: nums = [1,2,3,4]
Output: 24
💡 Note: Maximum product from three largest: 2 × 3 × 4 = 24
Example 3 — Mixed Signs
$ Input: nums = [-1,-2,-3]
Output: -6
💡 Note: All negative numbers: (-1) × (-2) × (-3) = -6

Constraints

  • 3 ≤ nums.length ≤ 104
  • -1000 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Maximum Product of Three Numbers INPUT Integer Array nums[] 1 idx: 0 2 idx: 1 3 idx: 2 Input Details nums = [1, 2, 3] Length: 3 elements Possible Products 1 x 2 x 3 = 6 (Only one combination) ALGORITHM STEPS (Single Pass Optimal) 1 Initialize Trackers Track max1, max2, max3 Track min1, min2 2 Single Pass Scan Update max/min values in one iteration 3 Compare Two Cases Case A: max1*max2*max3 Case B: min1*min2*max1 4 Return Maximum max(Case A, Case B) Tracked Values (Example) max1=3, max2=2, max3=1 min1=1, min2=2 Result: max(6, 6) = 6 FINAL RESULT Selected Three Numbers 1 x 2 x 3 Output: 6 OK - Maximum Product 1 x 2 x 3 = 6 Complexity Time: O(n) | Space: O(1) Key Insight: The maximum product can come from either: (1) Three largest positive numbers, OR (2) Two smallest negatives (large product) multiplied by the largest positive. Single pass tracks 3 max and 2 min values -- no sorting needed for O(n) solution! TutorialsPoint - Maximum Product of Three Numbers | Single Pass Optimal Approach
Asked in
Amazon 25 Microsoft 18 Apple 12
35.0K Views
Medium Frequency
~15 min Avg. Time
890 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