Sum of Subarray Ranges

medium array stack monotonic stack

Problem

Return the sum of (max − min) over every contiguous subarray of nums. Use two monotonic-stack passes: each element's contribution to sum-of-maxes minus sum-of-mins, weighted by counts of subarrays where it dominates.

Inputnums = [1, 2, 3]
Output4
Subarrays: [1]0,[2]0,[3]0,[1,2]1,[2,3]1,[1,2,3]2 → 4.

def sub_array_ranges(nums):
    n = len(nums)
    total = 0
    for i in range(n):
        mn = mx = nums[i]
        for j in range(i, n):
            mn = min(mn, nums[j])
            mx = max(mx, nums[j])
            total += mx - mn
    return total
function subArrayRanges(nums) {
  const n = nums.length;
  let total = 0;
  for (let i = 0; i < n; i++) {
    let mn = nums[i], mx = nums[i];
    for (let j = i; j < n; j++) {
      mn = Math.min(mn, nums[j]);
      mx = Math.max(mx, nums[j]);
      total += mx - mn;
    }
  }
  return total;
}
class Solution {
    public long subArrayRanges(int[] nums) {
        int n = nums.length;
        long total = 0;
        for (int i = 0; i < n; i++) {
            int mn = nums[i], mx = nums[i];
            for (int j = i; j < n; j++) {
                mn = Math.min(mn, nums[j]);
                mx = Math.max(mx, nums[j]);
                total += mx - mn;
            }
        }
        return total;
    }
}
long long subArrayRanges(vector<int>& nums) {
    int n = nums.size();
    long long total = 0;
    for (int i = 0; i < n; i++) {
        int mn = nums[i], mx = nums[i];
        for (int j = i; j < n; j++) {
            mn = min(mn, nums[j]);
            mx = max(mx, nums[j]);
            total += mx - mn;
        }
    }
    return total;
}
Time: O(n²) (or O(n) via monotonic stacks) Space: O(n)