Maximum Subarray Min-Product - Problem

The min-product of an array is equal to the minimum value in the array multiplied by the array's sum.

For example, the array [3,2,5] (minimum value is 2) has a min-product of 2 * (3+2+5) = 2 * 10 = 20.

Given an array of integers nums, return the maximum min-product of any non-empty subarray of nums. Since the answer may be large, return it modulo 109 + 7.

Note that the min-product should be maximized before performing the modulo operation. Testcases are generated such that the maximum min-product without modulo will fit in a 64-bit signed integer.

A subarray is a contiguous part of an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,2]
Output: 14
💡 Note: The subarray [2,3,2] has minimum 2 and sum 7, giving min-product = 2 × 7 = 14, which is maximum among all subarrays.
Example 2 — Single Element
$ Input: nums = [2,3,3,1,2]
Output: 18
💡 Note: The subarray [2,3,3] has minimum 2 and sum 8, giving min-product = 2 × 8 = 16. But [3,3] has min-product = 3 × 6 = 18.
Example 3 — Large Numbers
$ Input: nums = [3,1,5,6,4,2]
Output: 60
💡 Note: The subarray [5,6,4] has minimum 4 and sum 15, giving min-product = 4 × 15 = 60, which is the maximum.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 107

Visualization

Tap to expand
Maximum Subarray Min-Product INPUT nums = [1, 2, 3, 2] 1 i=0 2 i=1 3 i=2 2 i=3 Example Subarray: [2, 3, 2] Min-Product Formula: min(arr) * sum(arr) = 2 * (2+3+2) = 2 * 7 = 14 Goal: Find MAX min-product ALGORITHM STEPS 1 Build Prefix Sum pre[i] = sum(nums[0..i]) pre = [0, 1, 3, 6, 8] 2 Monotonic Stack Find left/right bounds For each element, find: - leftSmaller[i] - rightSmaller[i] 3 Calculate Min-Products For each as minimum For nums[1]=2 (min in [2,3,2]): sum = pre[4] - pre[1] = 8-1 = 7 minProd = 2 * 7 = 14 4 Track Maximum Return max % (10^9+7) Time: O(n) | Space: O(n) Stack processes each element once FINAL RESULT Output: 14 Verification: Min-Products for each min: nums[0]=1: range[0,3] 1*(1+2+3+2)=8 nums[1]=2: range[1,3] 2*(2+3+2)=14 [OK] nums[2]=3: range[2,2] 3*3=9 nums[3]=2: range[3,3] 2*2=4 Maximum = 14 from subarray [2,3,2] Key Insight: For each element as the MINIMUM, use monotonic stack to find the largest subarray where it remains minimum. The stack efficiently finds left and right boundaries in O(n). Prefix sums allow O(1) range sum queries. TutorialsPoint - Maximum Subarray Min-Product | Optimal Solution
Asked in
Google 25 Amazon 18 Microsoft 15 Apple 12
28.4K Views
Medium Frequency
~25 min Avg. Time
982 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen