Skip to content

Commit 0f4e7cd

Browse files
committed
Optimized brute force approach
1 parent 0eb48f9 commit 0f4e7cd

File tree

1 file changed

+4
-11
lines changed

1 file changed

+4
-11
lines changed
Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,16 @@
1-
var maxProduct = function (nums) { // brute force approach
2-
let subarrays = [];
1+
var maxProduct = function (nums) { // brute force approach - doesn't pass leetcode (Time Limit Exceeded)
2+
let maxProduct = -Infinity;
33
for (let i = 0; i < nums.length; i++) { // get subarrays
44
for (let j = i; j < nums.length; j++) {
5-
subarrays.push(nums.slice(i, j + 1));
5+
let prod = nums.slice(i, j + 1).reduce((acc, el) => acc *= el, 1);
6+
maxProduct = Math.max(prod, maxProduct);
67
}
78
}
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-
159
return maxProduct;
1610
};
1711

1812
// time - O(n^2) double for loop
1913
// space - O(n^2) total count of subarrays = n*(n+1)/2
2014

2115

22-
2316
// TODO - different approach

0 commit comments

Comments
 (0)