Maximum Product of Three Numbers

Given an integer array nums, pick three numbers whose product is as large as possible and return that product.

30:00

Maximum Product of Three Numbers
easy
Free written solution
Topics
Companies

Given an integer array nums, pick three numbers whose product is as large as possible and return that product.

Example 1:
Input: {"nums":[1,2,3]}
Output: 6
Constraints:
  • 3≤nums.length≤1043 \leq \text{nums.length} \leq 10^4

  • −1000≤nums[i]≤1000-1000 \leq \text{nums}[i] \leq 1000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,3]}

Only five numbers matter: the three largest and the two smallest. Start every slot empty and scan once.

one pass over nums · 0/3 read

1

0

2

1

3

2

three largest so far

—

max1

—

max2

—

max3

two smallest so far

—

min1

—

min2

the two candidates

max1 · max2 · max3

? · ? · ?

min1 · min2 · max1

? · ? · ?

Variables
VariableValue
max1-
max2-
max3-
min1-
min2-
DepthFunction Call
Stack empty
0/5