Sum of Subarray Ranges
Problem Statement
You are given an integer array nums. The range of a subarray is its largest element minus its smallest element.
Return the sum of the ranges of all contiguous subarrays of nums.
An integer array nums.
One 64-bit integer: the sum of (max − min) over every subarray.
Ranges: [1]=0, [2]=0, [3]=0, [1,2]=1, [2,3]=1, [1,2,3]=2. Total 4.
Ranges: [1]=0, [3]=0, [3]=0, [1,3]=2, [3,3]=0, [1,3,3]=2. Total 4.
Adding (max − min) over all 15 subarrays gives 59.
- • 1 ≤ nums.length ≤ 1000
- • −10^9 ≤ nums[i] ≤ 10^9
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Fix the start, extend the end, add (running max − running min)
Two monotonic stack passes: each element times the number of subarrays it is the max (or min) of
Fix the start. Move the end right one step at a time, updating the running min and max. Each step is one subarray, so add max − min to the total.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Monotonic Stack translate into production architectures and low-level memory mechanics.