Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
From Brute Force to Optimal: Subarray Ranges Explained via Monotonic Stacks š„
May 17, 2025
45 views
Written by Prashant Basnet
Prashant Basnet, a software engineer at Unisala.com, focuses on software development and enjoys building platforms to share knowledge. Interested in system design, data structures, and is currently learning NLP
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.
Example 1:
Example 2:
Example 3:
Situation:
Task:
Action:
š ļø Brute Force Approach:
ā” Optimization Insight
Optimized Solution O(n) Using Monotonic Stacks:
Instead of computing the range (max - min) for each subarray, flip the approach:
Use these to compute total contribution of each element to the final sum. Each element contributes to the total as:
We can use monotonic stack
1. For next smaller elements
2. For prev smaller elements
3. Now finding the maxSum
4. For next greater elements
5. For prev greater elements
š Conclusion:
Instead of brute-forcing all subarrays, we flipped the problem:
Using monotonic stacks, we tracked that efficiently and summed their contributions.
š§ Master this pattern and you'll unlock a whole new level in:
Next time you're stuck with O(n²), think: ā”ļø "Can I reframe it in terms of element contribution?