Code:
int cmpfunc (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int solution(int A[], int N) {
long product = A[0] * A[1] * A[2];
if (N == 3) {
return product;
}
// Nlog(N)
qsort(A, N, sizeof(int), cmpfunc);
if (A[N - 3] >= 0) {
// if there is at least 3 non-negative value
// then take three maximum values
product = A[N - 1] * A[N - 2] * A[N - 3];
if (A[1] < 0) {
// if there is at least 2 negative value
if (product < A[N - 1] * A[0] * A[1]) {
// then take maximum positive and two minimum negative, if that is more than 3 positive values
product = A[N - 1] * A[0] * A[1];
}
}
} else if (A[N - 1] >= 0) {
// else if there is least 1 non-negative value
// then take maximum positive and two minimum negative
product = A[N - 1] * A[0] * A[1];
} else {
// otherwise, take 3 maximum negative values
product = A[N - 1] * A[N - 2] * A[N - 3];
}
return product;
}
Output:
Execute and get the output.
More Java Programs: