forked from anitaa1990/Android-Cheat-sheet
-
Notifications
You must be signed in to change notification settings - Fork 2
/
FindMaxProduct.java
31 lines (23 loc) · 781 Bytes
/
FindMaxProduct.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package arrays;
import java.util.Arrays;
public class FindMaxProduct {
/*
* Find the 3 numbers in an array that produce the max product
* Input: {10, 3, 5, 6, 20}
* Output: 1200
* */
public static int findMaxProduct(int arr[], int n) {
if (n < 3) return -1;
// Sort the array in ascending order
Arrays.sort(arr);
// Return the maximum of product of last three
// elements and product of first two elements
// and last element
return Math.max(arr[0] * arr[1] * arr[n - 1],
arr[n - 1] * arr[n - 2] * arr[n - 3]);
}
public static void main(String[] args) {
int[] arr = {10, 3, 5, 6, 20};
System.out.println(findMaxProduct(arr, arr.length));
}
}