oneby7

Stacks and Queues Monotonic stack

217. Sum of Subarray Ranges

Medium

You are given an array of integers nums. The range of a subarray is its largest element minus its smallest element. Return the sum of the ranges of all the subarrays of nums.

A subarray is a contiguous run of one or more elements. Two subarrays are different if they start or end at different positions, even when they hold the same values. A subarray of one element has range 0.

Example 1

Input: nums = [3, 1, 4, 2]

Output: 16

Explanation: The four single elements have range 0. The pairs [3,1], [1,4] and [4,2] have ranges 2, 3 and 2. [3,1,4], [1,4,2] and the whole array each have range 4 − 1 = 3. The total is 7 + 9 = 16.

Example 2

Input: nums = [2, 2, 2]

Output: 0

Explanation: Every subarray holds only 2s, so its largest and smallest elements are equal and its range is 0.

Example 3

Input: nums = [-500000000, 500000000, -500000000]

Output: 3000000000

Explanation: The three subarrays longer than one element each hold both values, so each has range 5 × 108 − (−5 × 108) = 109.

Check your understanding

Work out the answer for this input before you write any code.

nums = [4, 1, 3]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -5 × 108 ≤ nums[i] ≤ 5 × 108

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.