Created
June 23, 2014 02:16
-
-
Save le-doude/f55638b9e6c419f9d312 to your computer and use it in GitHub Desktop.
This is my solution to the https://codility.com/demo/take-sample-test/max_product_of_three
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
package maxProductOfThree; | |
import java.util.Arrays; | |
import static java.lang.Math.*; | |
public class Solution { | |
public int solution(int[] A) { | |
if (A != null && A.length > 3) { | |
int[] maxes = {A[0], A[1], A[2]}; | |
Arrays.sort(maxes); | |
int mins[] = {maxes[0], maxes[1]}; | |
for (int i = 3; i < A.length; i++) { | |
if (A[i] > maxes[2]) { | |
maxes[0] = maxes[1]; | |
maxes[1] = maxes[2]; | |
maxes[2] = A[i]; | |
} else if (A[i] > maxes[1]) { | |
maxes[0] = maxes[1]; | |
maxes[1] = A[i]; | |
} else if (A[i] > maxes[0]) { | |
maxes[0] = A[i]; | |
} | |
if (A[i] < mins[0]) { | |
mins[1] = mins[0]; | |
mins[0] = A[i]; | |
} else if (A[i] < mins[1]) { | |
mins[1] = A[i]; | |
} | |
} | |
return max(maxes[2] * maxes[1] * maxes[0], maxes[2] * mins[1] * mins[0]); | |
} else { | |
int[] maxes = new int[3]; | |
Arrays.fill(maxes, 1); | |
for (int i = 0; i < A.length; i++) { | |
maxes[i] = A[i]; | |
} | |
return maxes[2] * maxes[1] * maxes[0]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment