Skip to content

Commit 02f3b0a

Browse files
committed
update: solution in O(n)
1 parent 1eda2e7 commit 02f3b0a

File tree

1 file changed

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

1 file changed

+37
-0
lines changed

src/_Problems_/max-product-of-3-numbers/index.js

+37
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,42 @@ function maxProductof3Numbers(arr) {
2424
// considering -ve numbers, 2 -ve on multiplication becomes +ve
2525
const p2 = arr[0] * arr[1] * arr[n - 1];
2626

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+
2764
return p1 > p2 ? p1 : p2;
2865
}

0 commit comments

Comments
 (0)