Skip to content

Commit 1eda2e7

Browse files
committed
update: new problem added
1 parent fde466a commit 1eda2e7

File tree

1 file changed

+28
-0
lines changed
  • src/_Problems_/max-product-of-3-numbers

1 file changed

+28
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)