Skip to content

Commit b3725d9

Browse files
Added forward and backward loop approach for 152 Maximum Product Sub-array
1 parent 7ac57e6 commit b3725d9

File tree

3 files changed

+41
-4
lines changed

3 files changed

+41
-4
lines changed

README.md

+18-4
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,39 @@ https://sebinsua.com/assets/posts/algorithmic-bathwater/algorithmic-bathwater-1.
77
# 152 Maximum Product Sub-array
88

99
Intuition:
10-
1. If array can have at most one negative, we can take same approach as #053 Maximum subarray
10+
1. If array can have at most one negative, we can take same approach as Kadane's Algo in #053 Maximum subarray
1111
2. When there are more then one negative number in sub-array,
1212
1. Positive number multiplication with negative number will make it negative
1313
2. Negative number multiplication with negative number will make it positive
14-
3. In that case need to tack, calculate and get min and max both for each element
14+
3. There are two approach
15+
1. First find the max product via kadane's algo form left to right and then max from right to left
16+
1. return the max of both
17+
2. track min and max
1518

19+
Approach #1 : Loop from both side in Kadane algo
20+
1. Loop from left to right
21+
1. find currProduct of currMax * n
22+
2. find max of currProduct and currMax
23+
3. if currProduct ==0, rest to 1
24+
2. Loop from right to left and repeat above steps
25+
3. compare the max of both the loop and return the max
1626

17-
Approach
27+
28+
Approach #2 : Track max and min in Kadane algo
1829
1. track max, min. Initialize it with 1
1930
2. track result and init with nums[0]
2031
3. for each number in array
21-
1. store temp = max * n // `because max will change after calculating the max`
32+
1. store temp = max // `because max will change after calculating the max`
2233
2. calculate max via max(max *n, min *n, n)
2334
3. calculate min via min(temp * n, min * n, n)
2435
4. calculate res = max(res, max)
2536
4. return res
2637

2738

2839

40+
41+
42+
2943
# 238. Product of Array Except Self
3044
Intuition: at every element, product to array except self will be the product of all the element before that element and product of all the element after that element.
3145

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution:
2+
def maxProduct(self, nums: List[int]) -> int:
3+
4+
result = float('-inf')
5+
6+
prod = 1
7+
for n in nums:
8+
prod *= n
9+
result = max(result, prod)
10+
if prod == 0:
11+
prod = 1
12+
13+
prod = 1
14+
for i in range(len(nums)-1, -1, -1):
15+
16+
prod *= nums[i]
17+
result = max(result, prod)
18+
if prod == 0:
19+
prod = 1
20+
21+
return result
22+
23+

0 commit comments

Comments
 (0)