- Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmaximum_product_subarray.py
44 lines (33 loc) · 1.32 KB
/
maximum_product_subarray.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
classSolution:
# main idea: dynamic programming (DP)
# Besides keeping track of the largest product,
# we also need to keep track of the smallest product.
# be careful: 'contiguous' subarray
defmy_product(self,nums):
# special case
iflen(nums)==1:
returnnums[0]
# initialization
my_max= [0for_inrange(len(nums))]
my_min= [0for_inrange(len(nums))]
print(my_max)
print(my_min)
# set the base
my_max[0] =nums[0]
my_min[0] =nums[0]
# need to initialize the 'final_max'
final_max=nums[0]
foriinrange(1, len(nums)):
# update 'max' and 'min'
my_max[i] =max(my_max[i-1]*nums[i], my_min[i-1]*nums[i], nums[i])
my_min[i] =min(my_max[i-1]*nums[i], my_min[i-1]*nums[i], nums[i])
# need to update the 'final_max'
final_max=max(final_max, my_max[i])
returnfinal_max
defmaxProduct(self, nums: List[int]) ->int:
# test case
#test_input = [-4,-3]
#test_result = self.my_product(test_input)
#print(test_result)
result=self.my_product(nums)
returnresult