Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find maximum subarray min-product in Python
Suppose we have an array nums, we need to find the maximum min-product of each non-empty subarray. The min-product of an array is equal to the minimum value in the array multiplied by the sum of the array. Since the answer can be large, we return it modulo 10^9+7.
For example, if we have an array [4,3,6], the minimum value is 3 and the sum is 13, so the min-product is 3 × 13 = 39.
Problem Example
If the input is nums = [2,3,4,3], the output will be 30. We can get the subarray [3,4,3] which gives us 3 × (3+4+3) = 3 × 10 = 30.
Algorithm Approach
We use a monotonic stack to efficiently find the maximum min-product ?
- Use a stack to maintain elements in increasing order
- For each element, pop larger elements and calculate their contribution
- Track running sum to quickly calculate subarray sums
- Add a sentinel value (0) to process remaining elements
Implementation
def solve(nums):
m = int(1e9 + 7)
stack = []
rsum = 0
res = 0
# Add sentinel value to process remaining elements
nums.append(0)
for i, v in enumerate(nums):
# Pop elements greater than or equal to current value
while stack and nums[stack[-1][0]] >= v:
index, _ = stack.pop()
# Calculate sum of subarray ending at current position
arrSum = rsum
# Subtract prefix sum if stack not empty
if stack:
arrSum = rsum - stack[-1][1]
# Update maximum min-product
res = max(res, nums[index] * arrSum)
# Add current value to running sum
rsum += v
# Push current index and running sum
stack.append((i, rsum))
return res % m
# Test the function
nums = [2, 3, 4, 3]
result = solve(nums)
print(f"Maximum min-product: {result}")
Maximum min-product: 30
How It Works
The algorithm works by maintaining a monotonic stack where elements are in non-decreasing order ?
- Stack maintains indices: Each element stores (index, running_sum)
- Pop larger elements: When we find a smaller element, pop all larger ones
- Calculate contribution: For each popped element, it becomes the minimum of some subarray
- Efficient sum calculation: Use running sum and prefix difference to get subarray sum
Example Walkthrough
For nums = [2,3,4,3,0] (after adding sentinel) ?
| Step | Current Element | Stack Action | Min-Product Calculated |
|---|---|---|---|
| 1 | 2 | Push (0,2) | - |
| 2 | 3 | Push (1,5) | - |
| 3 | 4 | Push (2,9) | - |
| 4 | 3 | Pop index 2 (value 4) | 4 × 4 = 16 |
| 5 | 0 | Pop remaining elements | 3 × 10 = 30 |
Conclusion
This monotonic stack approach efficiently finds the maximum min-product in O(n) time complexity. The key insight is using each element as the minimum value of subarrays and calculating their contributions systematically.
---