Sum of Subarray Ranges

Medium · Stack & Strings · Array · Stack · Monotonic Stack

Problem

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 non-empty contiguous subarrays of nums.

The answer can exceed 32 bits, so use a 64-bit integer where your language needs one.

Examples

Input: nums = [2,4,1]
Output: 8

Single elements have range 0, while [2,4], [4,1] and [2,4,1] have ranges 2, 3 and 3.

Input: nums = [1,-2,5]
Output: 17

The ranges of [1,-2], [-2,5] and [1,-2,5] are 3, 7 and 7.

Input: nums = [3,3,3]
Output: 0

Every subarray has equal elements, so every range is 0.

Constraints

Approaches

Follow-up

What about subsequences instead of subarrays? Then order stops mattering: sort, and each element is the maximum of 2^i subsequences and the minimum of 2^(n-1-i) (see the use case “Sum of ranges over every subsequence”).

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…