File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*-------------------------------
2
+ Time Complexity: O(n)
3
+ Space Complexity: O(1)
4
+ -------------------------------*/
5
+ class Solution {
6
+ public int maxProductDifference (int [] nums ) {
7
+ int max1 = 0 , max2 = 0 ;
8
+ int min1 = Integer .MAX_VALUE , min2 = Integer .MAX_VALUE ;
9
+
10
+ for (int n : nums ){
11
+ if (n > max2 ){
12
+ if (n > max1 ){
13
+ max2 = max1 ;
14
+ max1 = n ;
15
+ }
16
+ else
17
+ max2 = n ;
18
+ }
19
+ if (n < min2 ){
20
+ if (n < min1 ){
21
+ min2 = min1 ;
22
+ min1 = n ;
23
+ }
24
+ else
25
+ min2 = n ;
26
+ }
27
+ }
28
+ return (max1 * max2 ) - (min1 * min2 );
29
+ }
30
+ }
31
+
32
+ /*------------------------------------
33
+ Time Complexity: O(nlog(n))
34
+ Space Complexity: O(1)
35
+ -------------------------------------*/
36
+ class Solution {
37
+ public int maxProductDifference (int [] nums ) {
38
+ Arrays .sort (nums );
39
+ int res = (nums [nums .length -1 ]*nums [nums .length -2 ]) - (nums [0 ]*nums [1 ]);
40
+ return res ;
41
+ }
42
+ }
You can’t perform that action at this time.
0 commit comments