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 ;
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
You can’t perform that action at this time.
0 commit comments