File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 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+ } ;
You can’t perform that action at this time.
0 commit comments