#K93837. Maximum Product of Three Numbers
Maximum Product of Three Numbers
Maximum Product of Three Numbers
You are given an array of integers representing the stability scores of scientists in a research team. Your task is to compute the maximum product achievable by multiplying the scores of any three distinct scientists. If the array contains fewer than three elements, output -1
.
The maximum product may come from either:
- Multiplying the three largest numbers.
- Multiplying the largest number with the two smallest numbers (which could be negative, resulting in a positive product).
Note: The solution is expected to run in O(n) time and O(1) extra space. The final answer should be printed to stdout.
Mathematical Formulation:
Let the three largest numbers be \( a, b, c \) and the two smallest be \( x, y \). Then the answer is given by:
[ \text{result} = \max(a \times b \times c,, a \times x \times y)]
inputFormat
The input is read from stdin and is formatted as follows:
- The first line contains an integer
n
denoting the number of scientists (elements in the array). - The second line contains
n
space-separated integers representing the stability scores.
outputFormat
Output a single integer which is the maximum product of any three distinct numbers from the input array. If there are fewer than three numbers, print -1
.
6
1 10 2 6 5 3
300