-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharrays10.py
68 lines (48 loc) · 1.67 KB
/
arrays10.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Given an array arr[] that contains positive and negative integers (may contain 0 as well). Find the maximum product that we can get in a subarray of arr[].
# Input: arr[] = [-2, 6, -3, -10, 0, 2]
# Output: 180
# Input: arr[] = [-1, -3, -10, 0, 6]
# Output: 30
# Input: arr[] = [2, 3, 4]
# Output: 24
# Time Complexity: O(n) and Space Complexity: O(1)
def maxProduct(arr):
n = len(arr)
maxProd = float('-inf')
# leftToRight to store product from left to Right
leftToRight = 1
# rightToLeft to store product from right to left
rightToLeft = 1
for i in range(n):
if leftToRight == 0:
leftToRight = 1
if rightToLeft == 0:
rightToLeft = 1
# calculate product from index left to right
leftToRight *= arr[i]
# calculate product from index right to left
j = n - i - 1
rightToLeft *= arr[j]
maxProd = max(leftToRight, rightToLeft, maxProd)
return maxProd
arr = [-2, 6, -3, -10, 0, 2]
print(maxProduct(arr))
# # Python program to find Maximum Product Subarray
# # using nested loops
# # Function to returns the product of max product subarray
# def maxProduct(arr):
# n = len(arr)
# # Initializing result
# result = arr[0]
# for i in range(n):
# mul = 1
# # traversing in current subarray
# for j in range(i, n):
# mul *= arr[j]
# # updating result every time
# # to keep track of the maximum product
# result = max(result, mul)
# return result
# if __name__ == "__main__":
# arr = [-2, 6, -3, -10, 0, 2]
# print(maxProduct(arr))