Skip to content

Commit 0eb48f9

Browse files
committed
Maximum Product Subarray solution
1 parent 8b3e245 commit 0eb48f9

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
var maxProduct = function (nums) { // brute force approach
2+
let subarrays = [];
3+
for (let i = 0; i < nums.length; i++) { // get subarrays
4+
for (let j = i; j < nums.length; j++) {
5+
subarrays.push(nums.slice(i, j + 1));
6+
}
7+
}
8+
9+
let maxProduct = 0;
10+
subarrays.forEach(arr => { // find product of each subarray and compare to maxProduct
11+
let prod = arr.reduce((acc, el) => acc *= el, 1);
12+
max = Math.max(prod, max);
13+
})
14+
15+
return maxProduct;
16+
};
17+
18+
// time - O(n^2) double for loop
19+
// space - O(n^2) total count of subarrays = n*(n+1)/2
20+
21+
22+
23+
// TODO - different approach

0 commit comments

Comments
 (0)