![]() |
VOOZH | about |
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 = 4Input: 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
Table of Content
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.
4
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:
To efficiently find next/previous greater and next/previous smaller elements, we use monotonic stacks.
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.