forked from andrei-punko/java-interview-coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxMultiplicationOf3InArray.java
More file actions
29 lines (23 loc) · 1013 Bytes
/
MaxMultiplicationOf3InArray.java
File metadata and controls
29 lines (23 loc) · 1013 Bytes
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
package by.andd3dfx.numeric;
import java.util.Arrays;
import java.util.stream.Collectors;
import static java.lang.Math.max;
/**
* Write method which takes array and returns max product of 3 numbers taken from this array
*
* @see <a href="https://youtu.be/wzO6abwg4y4">Video solution</a>
*/
public class MaxMultiplicationOf3InArray {
public static long find(int[] arr) {
if (arr.length < 3) {
throw new IllegalArgumentException("Input array should contain at least 3 elements!");
}
var list = Arrays.stream(arr).boxed().sorted().collect(Collectors.toList());
int size = list.size();
var max1 = list.get(size - 3) * list.get(size - 2) * list.get(size - 1);
var max2 = list.get(0) * list.get(size - 2) * list.get(size - 1);
var max3 = list.get(0) * list.get(1) * list.get(size - 1);
var max4 = list.get(0) * list.get(1) * list.get(2);
return max(max1, max(max2, max(max3, max4)));
}
}