Sum of Subarray Ranges - Problem
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray.
Return the sum of all subarray ranges of nums.
A subarray is a contiguous non-empty sequence of elements within an array.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,3]
›
Output:
4
💡 Note:
Subarrays: [1] (range=0), [2] (range=0), [3] (range=0), [1,2] (range=1), [2,3] (range=1), [1,2,3] (range=2). Sum = 0+0+0+1+1+2 = 4
Example 2 — Same Elements
$
Input:
nums = [1,3,3]
›
Output:
4
💡 Note:
Subarrays: [1] (range=0), [3] (range=0), [3] (range=0), [1,3] (range=2), [3,3] (range=0), [1,3,3] (range=2). Sum = 0+0+0+2+0+2 = 4
Example 3 — Single Element
$
Input:
nums = [4]
›
Output:
0
💡 Note:
Only one subarray [4] with range = 4-4 = 0
Constraints
- 1 ≤ nums.length ≤ 1000
- -109 ≤ nums[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Given array [1,2,3]
2
Generate Subarrays
Find all contiguous subarrays and their ranges
3
Sum Ranges
Add up all the ranges: 0+1+2+0+1+0 = 4
Key Takeaway
🎯 Key Insight: Each element's contribution depends on how many subarrays it appears in as maximum vs minimum
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code