Sum of Subarray Minimums

Stack / Queues Monotonic Stack Medium

Given an array of integers arr of size n, calculate the sum of the minimum value in each (contiguous) subarray of arr. Since the result may be large, return the answer modulo 109 +7.

Examples:

Input: arr = [3, 1, 2, 5]

Output: 18

Explanation: The minimum of subarrays: [3], [1], [2], [5], [3, 1], [1, 2], [2, 5], [3, 1, 2], [1, 2, 5], [3, 1, 2, 5] are 3, 1, 2, 5, 1, 1, 2, 1, 1, 1 respectively and their sum is 18.

Input: arr = [2, 3, 1]

Output: 10

Explanation: The minimum of subarrays: [2], [3], [1], [2,3], [3,1], [2,3,1] are 2, 3, 1, 2, 1, 1 respectively and their sum is 10.

Input: arr = [11, 81, 94, 43, 3]

Constraints

  •   1 <= arr.length <= 105
  •   1 <= arr[i] <= 106

Hints

  • Instead of generating all subarrays, count how many times each element is the minimum in different subarrays. Use a monotonic increasing stack to determine for each element.
  • Traverse left to right using a monotonic increasing stack to compute L[i]. Traverse right to left using a monotonic increasing stack to compute R[i].

Company Tags

Cerner Micron Technology Alibaba Etsy Stripe Splunk Epic Systems Mastercard Rakuten Byju's Reddit Nutanix Texas Instruments Walmart Johnson & Johnson PwC Twilio Epic Games Roblox Boston Consulting Group Unity Technologies Ernst & Young Siemens Healthineers eBay Swiggy Google Microsoft Amazon Meta Apple Netflix Adobe