-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathmaximum-product-of-two-elements-in-an-array
56 lines (53 loc) · 1.77 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
Approach 1
Time Complexity: O(nlogn)
*/
class Solution {
public int maxProduct(int[] nums) {
Arrays.sort(nums); //O(nlogn) time complexity sorting quick sort
return (nums[nums.length-1]-1)*(nums[nums.length-2]-1);
}
}
/*
Approach 2
Time Complexity: O(n)
*/
class Solution {
public int maxProduct(int[] nums) {
int[] arr=new int[2];
arr[0]=nums[0];//take array of size 2 store maximum two elements as we traverse through the array.
arr[1]=nums[1];
//Once traversing the array has O(n) time complexity
for(int i=2;i<nums.length;i++){
//if both stored elements are smaller than the nums[i], replace the smaller one with nums[i]
if(nums[i]>arr[0] && nums[i]>arr[1]){
if(arr[0]<arr[1]){
arr[0]=nums[i];
}
else arr[1]=nums[i];
}
//else if only one element is smaller then replace that with nums[i]
else if(nums[i]>arr[0]){
arr[0]=nums[i];
}
else if(nums[i]>arr[1]){
arr[1]=nums[i];
}
}
return (arr[0]-1)*(arr[1]-1);
}
}
/*
Approach 3
Time complexity: O(n) using PriorityQueue
*/
class Solution {
public int maxProduct(int[] nums) {
PriorityQueue<Integer>pq=new PriorityQueue<>();
for(int num:nums){
pq.offer(num);
if(pq.size()>2)pq.poll();
}
return (pq.poll()-1)*(pq.poll()-1);
}
}