Skip to content

Instantly share code, notes, and snippets.

@tiagopereira17
Created July 6, 2016 16:06
Show Gist options
  • Save tiagopereira17/c1c78892dc7366e99c75fe73f99054ce to your computer and use it in GitHub Desktop.
Save tiagopereira17/c1c78892dc7366e99c75fe73f99054ce to your computer and use it in GitHub Desktop.
Maximize A[P] * A[Q] * A[R] for any triplet (P, Q, R).
import java.util.Arrays;
public class MaxProductOfThree {
public int solution(int[] A) {
if(A == null || A.length < 3) {
return 0;
}
Arrays.sort(A);
int lastIndex = A.length - 1;
int bigestElements = A[lastIndex] * A[lastIndex - 1] * A[lastIndex - 2];
int twoBigestNegs = A[0] * A[1] * A[lastIndex];
int maxProduct = Math.max(bigestElements, twoBigestNegs);
return maxProduct;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment