Sum of Subarray Ranges — LeetCode 2104 Python Solution

MediumStackArrayMonotonic Stack
Problem
#2104
Pattern
Stack
Reading time
2 min

The problem

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.

Example

Input
nums = [1,2,3]
Output
4
Explanation
The 6 subarrays of nums are the following:

Python solution

Python
class Solution:
    def subArrayRanges(self, nums: List[int]) -> int:
        ans, n = 0, len(nums)
        for i in range(n - 1):
            mi = mx = nums[i]
            for j in range(i + 1, n):
                mi = min(mi, nums[j])
                mx = max(mx, nums[j])
                ans += mx - mi
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2104. Sum of Subarray Ranges is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2104. Sum of Subarray Ranges?
LeetCode 2104. Sum of Subarray Ranges is rated Medium on LeetCode.
What is the time complexity of LeetCode 2104. Sum of Subarray Ranges?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2104. Sum of Subarray Ranges?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2104. Sum of Subarray Ranges cover?
LeetCode 2104. Sum of Subarray Ranges is tagged Stack, Array and Monotonic Stack on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview