File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Time Complexity: O(N) - just one pass through the array, so it's linear time.
2
+ # Space Complexity: O(1) - no extra arrays, just a few variables.
3
+
4
+ class Solution :
5
+ def maxProduct (self , nums : List [int ]) -> int :
6
+ # tracking max product from both ends
7
+ prefix_product , suffix_product = 1 , 1
8
+ # start with the biggest single number
9
+ max_product = max (nums )
10
+
11
+ for i in range (len (nums )):
12
+ # move forward, multiplying
13
+ prefix_product *= nums [i ]
14
+ # move backward, multiplying
15
+ suffix_product *= nums [len (nums ) - i - 1 ]
16
+ # update max product
17
+ max_product = max (max_product , prefix_product , suffix_product )
18
+
19
+ # if hit zero, reset to 1 (zero kills the product chain)
20
+ if prefix_product == 0 :
21
+ prefix_product = 1
22
+ if suffix_product == 0 :
23
+ suffix_product = 1
24
+
25
+ return max_product
You can’t perform that action at this time.
0 commit comments