Sum of Subarray Ranges

Medium · Stack & Monotonic Stack · about 25 minutes

Asked at Amazon, Meta, Google, Apple, Microsoft.

The range of a subarray is its largest element minus its smallest. Return the sum of the ranges of all contiguous subarrays of nums. The answer fits in a 64-bit integer; here it fits in 32 bits.

Related guides