File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public int maxProduct (int [] nums ) {
3+ int n = nums .length ;
4+ int [][] product = new int [2 ][n ];
5+ product [0 ][0 ] = nums [0 ];
6+ product [1 ][0 ] = nums [0 ];
7+ int max = nums [0 ];
8+ for (int i = 1 ; i < n ; i ++) {
9+ product [0 ][i ] = Math .max (product [0 ][i -1 ]*nums [i ], Math .max (nums [i ], nums [i ] * product [1 ][i -1 ]));
10+ product [1 ][i ] = Math .min (product [0 ][i -1 ]*nums [i ], Math .min (nums [i ], nums [i ] * product [1 ][i -1 ]));
11+ max =Math .max (max , product [0 ][i ]);
12+ }
13+ return max ;
14+ }
15+ }
16+ /**
17+
18+
19+ brute force :
20+ nested for loop
21+ tc : O(n^2)
22+ sc : O(1)
23+
24+ better sol :
25+ maintain min and max
26+ tc : O(n)
27+ sc : O(n)
28+
29+ compare with prev Min * cur, prevMax * cur, cur
30+ we have to keep track of minimum value that can lead to maximum value
31+ when there are negative values later.
32+
33+ 2 3 -2 4
34+ 2 6 -2 4
35+ 2 2 -12 -48
36+
37+ -2 0 -1
38+ -2 0 0
39+ -2 0 -1
40+
41+ 2 3 -2 5 7 -100
42+ 2 6 -2 5 35 210000
43+ 2 3 -6 -30 -210. -35
44+
45+ */
You can’t perform that action at this time.
0 commit comments