File tree Expand file tree Collapse file tree 1 file changed +4
-11
lines changed Expand file tree Collapse file tree 1 file changed +4
-11
lines changed Original file line number Diff line number Diff line change 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 ;
3
3
for ( let i = 0 ; i < nums . length ; i ++ ) { // get subarrays
4
4
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 ) ;
6
7
}
7
8
}
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
9
return maxProduct ;
16
10
} ;
17
11
18
12
// time - O(n^2) double for loop
19
13
// space - O(n^2) total count of subarrays = n*(n+1)/2
20
14
21
15
22
-
23
16
// TODO - different approach
You can’t perform that action at this time.
0 commit comments