-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMaximumProductDifferenceBetweenTwoPairs1913.java
More file actions
54 lines (48 loc) · 1.52 KB
/
MaximumProductDifferenceBetweenTwoPairs1913.java
File metadata and controls
54 lines (48 loc) · 1.52 KB
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
import java.util.Arrays;
public class MaximumProductDifferenceBetweenTwoPairs1913 {
public int maxProductDifference(int[] nums) {
// Brute Force
Arrays.sort(nums);
int n = nums.length;
return (nums[n - 1] * nums[n - 2]) - (nums[0] * nums[1]);
}
public int maxProductDifference2(int[] nums) {
// Optimized
int max1 = Integer.MIN_VALUE;
int max2 = Integer.MIN_VALUE;
int min1 = Integer.MAX_VALUE;
int min2 = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > max1) {
max2 = max1;
max1 = nums[i];
} else if (nums[i] > max2) {
max2 = nums[i];
}
if (nums[i] < min1) {
min2 = min1;
min1 = nums[i];
} else if (nums[i] < min2) {
min2 = nums[i];
}
}
return (max1 * max2) - (min1 * min2);
}
private int[] getMaxMin(int[] nums) {
int len = nums.length;
int maxi = 0, mini = 0, max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
for (int i = 0; i < len; i++) {
if (nums[i] > max) {
max = nums[i];
maxi = i;
}
if (nums[i] < min && nums[i] != Integer.MIN_VALUE) {
min = nums[i];
mini = i;
}
}
nums[maxi] = Integer.MIN_VALUE;
nums[mini] = Integer.MIN_VALUE;
return new int[] { max, min };
}
}