File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed
src/_Problems_/max-product-of-3-numbers Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Given an array of numbers where the length can atmost be 10^4
3
+ * Find the maximum product of 3 numbers
4
+ * Samples:
5
+ * [1, 2, 3] - 6
6
+ * [-10, 10, 2, 3] - 60
7
+ * [-10, -10, 2, 3] - 300
8
+ */
9
+
10
+ /** The following solution is O(nlogn) because of sorting */
11
+ function maxProductof3Numbers ( arr ) {
12
+ if ( ! Array . isArray ( arr ) ) {
13
+ throw new Error ( 'Invalid Argument' ) ;
14
+ }
15
+
16
+ // sort the array
17
+ arr . sort ( ( a , b ) => a - b ) ;
18
+
19
+ const n = arr . length ;
20
+
21
+ // when the numbers are all positive
22
+ const p1 = arr [ n - 1 ] * arr [ n - 2 ] * arr [ n - 3 ] ;
23
+
24
+ // considering -ve numbers, 2 -ve on multiplication becomes +ve
25
+ const p2 = arr [ 0 ] * arr [ 1 ] * arr [ n - 1 ] ;
26
+
27
+ return p1 > p2 ? p1 : p2 ;
28
+ }
You can’t perform that action at this time.
0 commit comments