forked from Nimesh-Srivastava/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1913.cpp
More file actions
44 lines (34 loc) · 944 Bytes
/
Copy path1913.cpp
File metadata and controls
44 lines (34 loc) · 944 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Solution 1
// Time : O(n logn)
class Solution {
public:
int maxProductDifference(vector<int>& nums) {
int siz = nums.size();
sort(nums.begin(), nums.end());
return (nums[siz-2] * nums[siz-1]) - (nums[0] * nums[1]);
}
};
// Solution 2
// Time : O(n)
class Solution {
public:
int maxProductDifference(vector<int>& nums) {
int max = INT_MIN, sub_max = INT_MIN;
int min = INT_MAX, sub_min = INT_MAX;
for(auto c : nums){
if(c > max){
sub_max = max;
max = c;
}
else if(c > sub_max)
sub_max = c;
if(c < min){
sub_min = min;
min = c;
}
else if(c < sub_min)
sub_min = c;
}
return (max * sub_max) - (min * sub_min);
}
};