Skills101
← All coding problems

Maximum Product of Three Numbers

easyArrays & Prefix Sums+10 XPTime limit 2s

Pick three different positions of the array so that the product of the three numbers is as large as possible. Print that product.

Input:

  • line 1: n
  • line 2: n integers

Output: the largest product of three elements.

Constraints: 3 ≤ n ≤ 10⁵, −1000 ≤ a[i] ≤ 1000.

Think about it: the three largest numbers are not always the answer — two big negative numbers multiply into a big positive one. After sorting, compare largest × second × third with smallest × second-smallest × largest. (You can also find these five numbers in one pass without sorting.)

Sample input 1

4
1 2 3 4

Sample output 1

24

Sample input 2

5
-10 -10 1 3 2

Sample output 2

300

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.