-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaxProductOfThree
63 lines (49 loc) · 1.86 KB
/
MaxProductOfThree
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//MaxProductOfThree
//A[P] * A[Q] * A[R] (0 <= P < Q < R < N).
public String maxProductOfThreeSolution(int[] A) {
Arrays.sort(A);
int n = A.length;
int maxWithNegativeNumbers = A[0] * A[1] * A[n - 1];
int maxWithPositiveNumbers = A[n - 3] * A[n - 2] * A[n - 1];
System.out.println(Math.max(maxWithNegativeNumbers, maxWithPositiveNumbers));
long prod = 0;
String arryVal = "";
for(int i=0; i<A.length; i++) {
int[] B = removeTheElement(A, i);
for(int j=0; j<B.length; j++) {
int[] C = removeTheElement(B, j);
for(int k=0; k<C.length; k++) {
//System.out.println(A[i] +":" +B[j]+":" +C[k] +"---->"+ (A[i] * B[j] * C[k]));
long sum = A[i] * B[j] * C[k];
if(sum >= prod) {
prod = sum;
arryVal = "Array index"+i+":"+j+":"+k+", Array index value "+A[i] +":" +B[j]+":" +C[k]+"";
}
}
}
}
return prod +": Array value:"+arryVal;
}
// Function to remove the element
public int[] removeTheElement(int[] arr, int index)
{
// Create another array of size one less
int[] anotherArray = new int[arr.length - 1];
// Copy the elements except the index
// from original array to the other array
for (int i = 0, k = 0; i < arr.length; i++) {
// if the index is
// the removal element index
if (i == index) {
continue;
}
// if the index is not
// the removal element index
anotherArray[k++] = arr[i];
}
//Java >8
//IntStream.range(0, arr.length).filter(i -> i != index).map(i -> arr[i]).toArray();
return anotherArray;
}
int[] g = {-3,1,2,-2,5,6,4,-4};
System.out.println("Max Product Of Three : "+obj.maxProductOfThreeSolution(g));