Skip to content

Commit 3276ce1

Browse files
committed
feat: 152. Maximum Product Subarray
1 parent 3481e87 commit 3276ce1

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Time complexity: O(n^2)
2+
// Space complexity: O(n)
3+
4+
/**
5+
* @param {number[]} nums
6+
* @return {number}
7+
*/
8+
var maxProduct = function (nums) {
9+
let answer = nums[0];
10+
11+
const productGroups = [[]];
12+
13+
for (let i = 0; i < nums.length; i++) {
14+
const productGroup = productGroups.at(-1);
15+
16+
if (nums[i] === 0) {
17+
productGroups.push([]);
18+
}
19+
20+
if (productGroup.length === 0) {
21+
productGroup.push(nums[i]);
22+
continue;
23+
}
24+
25+
productGroup.push(nums[i] * productGroup.at(-1));
26+
}
27+
28+
for (const group of productGroups) {
29+
for (let i = 0; i < group.length; i++) {
30+
answer = Math.max(answer, group[i]);
31+
32+
for (let j = 0; j < i; j++) {
33+
answer = Math.max(answer, group[i] / group[j]);
34+
}
35+
}
36+
}
37+
38+
return answer;
39+
};

0 commit comments

Comments
 (0)