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
271 views
Written by Prashant Basnet
š Welcome, Youāve Landed on My Signature Page.
Iām a Software Development Engineer passionate about building scalable systems and solving problems.
Beyond engineering, I enjoy sharing ideas and documenting lessons so others can learn and build on them.This space is my digital notebook, a place where I reflect on what Iām learning and creating.
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?