You are given an integer array `nums`. The range of a subarray is the difference between its largest and smallest element. Return the sum of the ranges of all subarrays of `nums`. A subarray is a contiguous non-empty sequence of elements. The answer can exceed 32 bits.
You are given an integer array nums. The range of a subarray is the difference between its largest and smallest element. Return the sum of the ranges of all subarrays of nums. A subarray is a contiguous non-empty sequence of elements. The answer can exceed 32 bits.
Example 1:
Input: {"nums":[1,2,3]}
Output: 4
Constraints:
1≤nums.length≤1000
−109≤nums[i]≤109
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"nums":[1,2,3]}
pass 1: Σ max (decreasing stack)
pass 2: Σ min (increasing stack)
1
0
2
1
3
2
Sum of (max - min) over all subarrays = (sum of every subarray max) - (sum of every subarray min). Count how many subarrays each element is the max of, then the min of.