Practice › Arrays
Maximum Product of Three Numbers
Easy · Arrays · Asked at Amazon, Microsoft, TCS, Infosys
Choose three elements at different positions and print the largest possible product.
Input
First line: n. Second line: n space-separated integers.
Output
The maximum product of three elements.
Constraints
- 3 ≤ n ≤ 10^5
- −1000 ≤ a[i] ≤ 1000
The answer is either the product of the three largest numbers, or the product of the two smallest (both possibly very negative) with the largest. One pass can track the top three and the bottom two.
Example 1
Input
4 1 2 3 4
Output
24
Example 2
Input
4 -10 -10 5 2
Output
500
Hints
- With only positive numbers, take the three largest.
- Two negative numbers multiply to a positive one.
- So compare (three largest) with (two smallest × the largest).
Approach
Sort the array (or track the top three and bottom two in one pass). The answer is max(a[n−1]·a[n−2]·a[n−3], a[0]·a[1]·a[n−1]). Any other choice is never better: the best triple either avoids negatives or uses exactly the two most negative numbers with the largest number.
Complexity: O(n log n) time with sorting (O(n) with one pass) · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<long long> a(n);
for (auto &x : a) cin >> x;
sort(a.begin(), a.end());
cout << max(a[n - 1] * a[n - 2] * a[n - 3], a[0] * a[1] * a[n - 1]) << "\n";
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
a = sorted(data[1 : 1 + data[0]])
print(max(a[-1] * a[-2] * a[-3], a[0] * a[1] * a[-1]))Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
long[] a = new long[n];
for (int i = 0; i < n; i++) {
in.nextToken();
a[i] = (long) in.nval;
}
Arrays.sort(a);
System.out.println(Math.max(a[n - 1] * a[n - 2] * a[n - 3], a[0] * a[1] * a[n - 1]));
}
}Solve Maximum Product of Three Numbers online · All practice problems