Sum of Subarray Ranges

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.

Follow-up: Could you find a solution with O(n) time complexity?

Example 1
Inputnums = [1,2,3]
Output4
The sum of the ranges over all 6 subarrays is 0 + 0 + 0 + 1 + 1 + 2 = 4.
Example 2
Inputnums = [1,3,3]
Output4
The sum of the ranges over all 6 subarrays is 0 + 0 + 0 + 2 + 0 + 2 = 4.

Constraints

  • 1 <= nums.length <= 1000
  • -10^9 <= nums[i] <= 10^9

Asked at 10 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate