We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent fde466a commit 1eda2e7Copy full SHA for 1eda2e7
src/_Problems_/max-product-of-3-numbers/index.js
@@ -0,0 +1,28 @@
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
+}
0 commit comments