File tree 1 file changed +37
-0
lines changed
src/_Problems_/max-product-of-3-numbers
1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change @@ -24,5 +24,42 @@ function maxProductof3Numbers(arr) {
24
24
// considering -ve numbers, 2 -ve on multiplication becomes +ve
25
25
const p2 = arr [ 0 ] * arr [ 1 ] * arr [ n - 1 ] ;
26
26
27
+ // return the largest of two probablities
28
+ return p1 > p2 ? p1 : p2 ;
29
+ }
30
+
31
+ /** The following solution is O(n) */
32
+ function maxProductof3NumbersII ( arr ) {
33
+ if ( ! Array . isArray ( arr ) ) {
34
+ throw new Error ( 'Invalid Argument' ) ;
35
+ }
36
+
37
+ let firstMax = ( secondMax = thirdMax = Number . MIN_SAFE_INTEGER ) ;
38
+ let firstMin = ( secondMin = Number . MAX_SAFE_INTEGER ) ;
39
+
40
+ for ( let i = 0 ; i < arr . length ; i += 1 ) {
41
+ if ( arr [ i ] > firstMax ) {
42
+ thirdMax = secondMax ;
43
+ secondMax = firstMax ;
44
+ firstMax = arr [ i ] ;
45
+ } else if ( arr [ i ] > secondMax ) {
46
+ thirdMax = secondMax ;
47
+ secondMax = arr [ i ] ;
48
+ } else if ( arr [ i ] > thirdMax ) {
49
+ thirdMax = arr [ i ] ;
50
+ }
51
+
52
+ // check for mins
53
+ if ( arr [ i ] < firstMin ) {
54
+ secondMin = firstMin ;
55
+ firstMin = arr [ i ] ;
56
+ } else if ( arr [ i ] < secondMin ) {
57
+ secondMin = arr [ i ] ;
58
+ }
59
+ }
60
+
61
+ const p1 = firstMax * secondMax * thirdMax ;
62
+ const p2 = firstMin * secondMin * firstMax ;
63
+
27
64
return p1 > p2 ? p1 : p2 ;
28
65
}
You can’t perform that action at this time.
0 commit comments