Find the maximum product of three numbers.
#include <limits.h>
#include <stddef.h>
long long max_product3(const int *a, size_t n) /* n >= 3 */
{
int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN; /* three largest */
int min1 = INT_MAX, min2 = INT_MAX; /* two smallest */
for (size_t i = 0; i < n; i++) {
int x = a[i];
if (x > max1) { max3 = max2; max2 = max1; max1 = x; }
else if (x > max2) { max3 = max2; max2 = x; }
else if (x > max3) { max3 = x; }
if (x < min1) { min2 = min1; min1 = x; }
else if (x < min2) { min2 = x; }
}
long long p1 = (long long)max1 * max2 * max3;
long long p2 = (long long)min1 * min2 * max1; /* two negatives make a positive */
return p1 > p2 ? p1 : p2;
}
/* {-10, -10, 1, 3, 2} -> 300 */
Points: the answer is either the three largest numbers or the two most negative times the largest; one pass, O(n), no sorting; use a 64-bit product to avoid overflow.