#1856
Maximum Subarray Min-Product
MediumArrayStackMonotonic StackPrefix SumMonotonic StackPrefix SumArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a monotonic stack to efficiently calculate the maximum min-product for each element in the array. This approach reduces the time complexity significantly by avoiding the need to check all subarrays explicitly.
⚙️
Algorithm
4 steps- 1Step 1: Create a prefix sum array to store the cumulative sums of nums.
- 2Step 2: Use a monotonic stack to find the next and previous smaller elements for each element in nums.
- 3Step 3: For each element, calculate the min-product using the prefix sums and the identified boundaries.
- 4Step 4: Keep track of the maximum min-product found and return it modulo 10^9 + 7.
solution.py30 lines
1# Full working Python code
2
3def maxSubarrayMinProduct(nums):
4 MOD = 10**9 + 7
5 n = len(nums)
6 prefix_sum = [0] * (n + 1)
7 for i in range(n):
8 prefix_sum[i + 1] = prefix_sum[i] + nums[i]
9
10 stack = []
11 max_product = 0
12 for i in range(n):
13 while stack and nums[stack[-1]] > nums[i]:
14 j = stack.pop()
15 left = stack[-1] if stack else -1
16 right = i
17 min_val = nums[j]
18 total_sum = prefix_sum[right] - prefix_sum[left + 1]
19 max_product = max(max_product, min_val * total_sum)
20 stack.append(i)
21
22 while stack:
23 j = stack.pop()
24 left = stack[-1] if stack else -1
25 right = n
26 min_val = nums[j]
27 total_sum = prefix_sum[right] - prefix_sum[left + 1]
28 max_product = max(max_product, min_val * total_sum)
29
30 return max_product % MODℹ
Complexity note: The time complexity is O(n) because we traverse the array and use the stack to find boundaries efficiently. The space complexity is O(n) due to the prefix sum array and the stack.
- 1Using prefix sums allows for quick calculation of subarray sums.
- 2Monotonic stacks help efficiently find boundaries for minimum values in subarrays.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.