VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-of-subarray-ranges-1/

⇱ Sum of Subarray Ranges - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of Subarray Ranges

Last Updated : 15 Sep, 2025

Given an integer array arr[], the range of a subarray is defined as the difference between the largest and smallest elements within that subarray. Find the sum of the ranges of all possible subarrays of the array.

Examples:

Input: arr[] = [1, 2, 3]
Output: 4
Explanation: All possible subarrays and their ranges are:
[1] → 1 - 1 = 0
[2] → 2 - 2 = 0
[3] → 3 - 3 = 0
[1, 2] → 2 - 1 = 1
[2, 3] → 3 - 2 = 1
[1, 2, 3] → 3 - 1 = 2
Sum of all ranges = 0 + 0 + 0 + 1 + 1 + 2 = 4

Input: arr[] = [-32, 0, -2, 72]
Output: 318
Explanation: All possible subarrays and their ranges are:
[-32] → -32 - (-32) = 0
[-32, 0] → 0 - (-32) = 32
[-32, 0, -2] → 0 - (-32) = 32
[-32, 0, -2, 72] → 72 - (-32) = 104
[0] → 0 - 0 = 0
[0, -2] → 0 - (-2) = 2
[0, -2, 72] → 72 - (-2) = 74
[-2] → -2 - (-2) = 0
[-2, 72] → 72 - (-2) = 74
[72] → 72 - 72 = 0
Sum of all ranges = 0 + 32 + 32 + 104 + 0 + 2 + 74 + 0 + 74 + 0 = 318

[Naive Approach] Computing in all subarray - O(n2) Time and O(1) Space

The idea is to generate all possible subarrays of the given array using two nested loops. For each subarray, we traverse through its elements to find the minimum and maximum values. Once these are identified, we calculate the difference between them, which gives the range of that subarray. We then add up the ranges of all subarrays to get the final result.


Output
4

[Expected Approach] Contribution of Each Element using Monotonic Stacks

Instead of calculating the min and max for each subarray individually, we calculate how much each element contributes to the sum of ranges.

For each element in the array:

  • Find the number of subarrays where it is the maximum.
  • Find the number of subarrays where it is the minimum.
  • The contribution of an element to the total sum is: contribution = (count as max - count as min) * element value
  • Sum all contributions of every element to get the final answer.

To efficiently find next/previous greater and next/previous smaller elements, we use monotonic stacks.


Output
4

Time Complexity: O(n), each element is pushed and popped from the stack at most once.
Auxiliary Space: O(n), for the stacks used to compute next/previous greater and smaller elements.

Comment
Article Tags:
Article Tags: