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
Sum of Subarray Ranges INPUT nums = [1, 2, 3] 1 idx: 0 2 idx: 1 3 idx: 2 All Subarrays: [1] range: 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 Total: 0+0+0+1+1+2 = 4 ALGORITHM STEPS 1 Initialize Set total_sum = 0 2 Outer Loop (i) Start each subarray at i 3 Inner Loop (j) Extend subarray to j 4 Track Min/Max Update min, max as j grows for i = 0 to n-1: min_val = max_val = nums[i] for j = i to n-1: min_val = min(min_val,nums[j]) max_val = max(max_val,nums[j]) sum += max_val - min_val return sum FINAL RESULT Iteration Trace: i,j Sub Min Max Rng 0,0 [1] 1 1 0 0,1 [1,2] 1 2 1 0,2 [1,2,3] 1 3 2 1,1 [2] 2 2 0 1,2 [2,3] 2 3 1 2,2 [3] 3 3 0 Sum: 0+1+2+0+1+0 = 4 OUTPUT 4 OK - Verified! Key Insight: By extending subarrays one element at a time (j loop), we can update min/max in O(1) instead of recalculating. This optimized brute force achieves O(n^2) time complexity with O(1) space - efficient for moderate input sizes. Range = max(subarray) - min(subarray). Track both values as the subarray grows to avoid redundant scans. TutorialsPoint - Sum of Subarray Ranges | Optimized Brute Force - Track Min/Max
Asked in
Google 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen