forked from Nikhil-2002/Programming_Hactoberfest23
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maximum-product-of-two-elements-in-an-array
36 lines (31 loc) · 1.11 KB
/
Maximum-product-of-two-elements-in-an-array
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
public class MaxProductOfTwoElements {
public static int maxProduct(int[] nums) {
int max1 = Integer.MIN_VALUE; // Maximum positive integer
int max2 = Integer.MIN_VALUE; // Second maximum positive integer
int min1 = Integer.MAX_VALUE; // Minimum negative integer
int min2 = Integer.MAX_VALUE; // Second minimum negative integer
for (int num : nums) {
if (num > max1) {
max2 = max1;
max1 = num;
} else if (num > max2) {
max2 = num;
}
if (num < min1) {
min2 = min1;
min1 = num;
} else if (num < min2) {
min2 = num;
}
}
// Calculate the maximum product
int product1 = max1 * max2;
int product2 = min1 * min2 * max1;
return Math.max(product1, product2);
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4};
int maxProduct = maxProduct(nums);
System.out.println("Maximum product of two elements: " + maxProduct);
}
}