Sum of Subarray Ranges

Stack / Queues Monotonic Stack Medium
  • Fact: The concept underlying this problem is extensively used in financial and data analysis software
  • In the finance industry, similar algorithms can be applied to analyze the volatility of stock prices over various sub periods
  • Likewise, in data analysis platforms, they can calculate metrics such as range of values over sliding windows
  • Calculating the range is a crucial part of identifying the spread of data which can provide insight into the level of variability or volatility within a dataset

Given an integer array nums, determine the range of a subarray, defined as the difference between the largest and smallest elements within the subarray. Calculate and return the sum of all subarray ranges of nums.


A subarray is defined as a contiguous, non-empty sequence of elements within the array.

Examples:

Input: nums = [1, 2, 3]

Output: 4

Explanation: The 6 subarrays of nums are the following:

[1], range = largest - smallest = 1 - 1 = 0 

[2], range = 2 - 2 = 0

[3], range = 3 - 3 = 0

[1,2], range = 2 - 1 = 1

[2,3], range = 3 - 2 = 1

[1,2,3], range = 3 - 1 = 2

So the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.

Input: nums = [1, 3, 3]

Output: 4

Explanation: The 6 subarrays of nums are the following:

[1], range = largest - smallest = 1 - 1 = 0

[3], range = 3 - 3 = 0

[3], range = 3 - 3 = 0

[1,3], range = 3 - 1 = 2

[3,3], range = 3 - 3 = 0

[1,3,3], range = 3 - 1 = 2

So the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.

Input: nums = [4, -2, -3, 4, 1]

Constraints

·  1 <= nums.length <= 1000

·  -109 <= nums[i] <= 109

Hints

  • Use two monotonic stacks. One to track next greater elements (for maximum contribution). Another to track next smaller elements (for minimum contribution).
  • Compute Left bound and Right Bound. The result is the difference between sum of maximum - minimum contributions.

Company Tags

Splunk Twilio Alibaba Optum Texas Instruments NVIDIA GE Healthcare Freshworks Deloitte Johnson & Johnson Zomato Roche Nutanix JPMorgan Chase OYO Rooms ARM PayPal HashiCorp Instacart Airbnb Intel Unity Technologies Teladoc Health Epic Systems Walmart Google Microsoft Amazon Meta Apple Netflix Adobe