Created
July 6, 2016 16:06
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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