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
167 views
Written by Prashant Basnet
<section class="bg-white dark:bg-gray-900 px-4 py-8 max-w-2xl mx-auto text-gray-800 dark:text-gray-200">
<h1 class="text-2xl sm:text-3xl font-signature italic font-semibold text-center mb-4">
👋 Welcome — You’ve Landed on My Signature Page
</h1>
<p class="text-base sm:text-lg mb-4">
Hey, I’m <strong class="text-black dark:text-white">Prashant Basnet</strong> — software developmemt engineer at
<a href="https://unisala.com" class="text-indigo-600 dark:text-indigo-400 underline hover:no-underline" target="_blank" rel="noopener noreferrer">
Unisala.com
</a>.
</p>
<p class="text-base sm:text-lg mb-6">
You’re viewing my <strong>Signature</strong>, a digital space where I share what I’m learning, building, and reflecting on, all in one place.
</p>
<div class="border-l-4 border-indigo-400 dark:border-indigo-500 pl-4 italic mb-6 text-sm sm:text-base text-gray-700 dark:text-gray-400">
📍 Found this page via LinkedIn, my personal site, or a shared link?
<br />
This isn’t a traditional portfolio. It’s my public digital notebook where I document useful ideas, experiments, and lessons I’ve learned as I build.
</div>
<h2 class="text-lg font-semibold mb-2">What You’ll Find Here:</h2>
<ul class="list-disc list-inside space-y-1 text-sm sm:text-base">
<li>✍️ Thoughts on algorithms, systems, and software design</li>
<li>🧠 Insights from building at Unisala</li>
<li>🔗 Direct links to everything I’ve published on Unisala</li>
</ul>
</section>
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?