惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Latest news
Latest news
T
Troy Hunt's Blog
V
Vulnerabilities – Threatpost
L
LINUX DO - 热门话题
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
V
V2EX
博客园 - 司徒正美
B
Blog RSS Feed
AWS News Blog
AWS News Blog
MyScale Blog
MyScale Blog
Scott Helme
Scott Helme
Cisco Talos Blog
Cisco Talos Blog
Last Week in AI
Last Week in AI
NISL@THU
NISL@THU
博客园 - Franky
P
Proofpoint News Feed
博客园_首页
C
CERT Recently Published Vulnerability Notes
雷峰网
雷峰网
S
Schneier on Security
P
Proofpoint News Feed
Hugging Face - Blog
Hugging Face - Blog
G
GRAHAM CLULEY
博客园 - 三生石上(FineUI控件)
月光博客
月光博客
WordPress大学
WordPress大学
The Hacker News
The Hacker News
T
Threatpost
阮一峰的网络日志
阮一峰的网络日志
A
Arctic Wolf
Microsoft Azure Blog
Microsoft Azure Blog
T
The Exploit Database - CXSecurity.com
Engineering at Meta
Engineering at Meta
罗磊的独立博客
T
The Blog of Author Tim Ferriss
D
Darknet – Hacking Tools, Hacker News & Cyber Security
I
Intezer
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
K
Kaspersky official blog
SecWiki News
SecWiki News
云风的 BLOG
云风的 BLOG
美团技术团队
C
Cybersecurity and Infrastructure Security Agency CISA
博客园 - 【当耐特】
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Security Latest
Security Latest
C
Cyber Attacks, Cyber Crime and Cyber Security
B
Blog
S
Security Affairs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
I Couldn't Optimize Max Sum Min-Product Until I Flipped the Question
Avinash Tyag · 2026-05-11 · via DEV Community

This is part of a series where I break down coding concepts I understand when reading about them but struggle to reuse when I actually need them. Not tutorials. Personal learning journeys that break down the "why does this actually work" part.

The problem that tripped me up

LeetCode 1856: Maximum Subarray Min-Product. The formula is straightforward. For any subarray, multiply the minimum element by the sum of the subarray. Find the maximum across all possible subarrays.

I could see the O(n^2) solution clearly. Try every subarray, track the running min and running sum, update the max. But dropping to O(n)? That's where I got stuck.

Where my intuition went wrong

My first instinct was a sliding window approach. Add an element to the range, check if it improves the answer, otherwise store the max and reset. It felt right because you're building ranges and checking them.

But here's why it fails: the decision to "keep going or reset" depends on both the sum AND the minimum changing at the same time. Adding a large number helps the sum but might not help if the min stays low. Adding a small number hurts the min but you don't know yet whether the sum makes up for it. There's no clean greedy condition to check.

I was stuck because I was asking the wrong question.

The reframe that made it click

Instead of asking "what's the best range?", flip it:

For each element, what's the widest subarray where THAT element is the minimum?

Why does this cover every possible answer? Because whatever the optimal subarray is, it has some minimum element. That minimum is one of the values in the array. So if you check every element as a potential minimum and find its best subarray, you're guaranteed to find the answer.

This changes the problem from "search all subarrays" to "for each element, find its boundaries." And finding boundaries is exactly what a monotonic stack does.

Diagram: An element finding its left and right boundaries

How the monotonic stack finds boundaries

You maintain a stack of indices where the values are strictly increasing from bottom to top. As you iterate through the array, when you encounter a value smaller than or equal to the stack top, you pop.

The magic: when an element gets popped, it has found both its boundaries in that single moment.

  • Right boundary: the current element (the one causing the pop). It's smaller, so the popped element can't be the minimum past this point.
  • Left boundary: whatever is now on top of the stack after popping. It's the nearest smaller element to the left.

The subarray where the popped element is the minimum goes from left_boundary + 1 to right_boundary - 1.

Let me trace through [3, 1, 6, 4, 5, 2]:

i=0, val=3: push 0          stack: [0]
i=1, val=1: pop 0, push 1   stack: [1]
  → popped 3: right=1, left=-1 (empty stack), subarray=[0..0]
i=2, val=6: push 2          stack: [1, 2]
i=3, val=4: pop 2, push 3   stack: [1, 3]
  → popped 6: right=3, left=1, subarray=[2..2]
i=4, val=5: push 4          stack: [1, 3, 4]
i=5, val=2: pop 4           stack: [1, 3]
  → popped 5: right=5, left=3, subarray=[4..4]
         pop 3              stack: [1]
  → popped 4: right=5, left=1, subarray=[2..4]

Enter fullscreen mode Exit fullscreen mode

When the stack is empty after popping, the left boundary is -1 (meaning "nothing smaller exists to the left, extend all the way to index 0"). After processing all elements, anything still in the stack has no right boundary, so it extends all the way to the end of the array (right boundary = n).

Prefix sums for O(1) range sums

Once you have boundaries for each element, you need the sum of that subarray. Building a prefix sum array with a leading zero handles this cleanly:

prefix = [0]
for num in nums:
    prefix.append(prefix[-1] + num)

# sum of nums[a..b] = prefix[b+1] - prefix[a]

Enter fullscreen mode Exit fullscreen mode

The leading zero is important. Without it, getting the sum starting from index 0 requires special-case handling that leads to off-by-one bugs (I know because I made this exact mistake).

The full solution

def maxSumMinProduct(self, nums):
    prefix = [0]
    for num in nums:
        prefix.append(prefix[-1] + num)

    result = 0
    stack = []

    for i in range(len(nums)):
        while stack and nums[stack[-1]] >= nums[i]:
            popped = stack.pop()
            left = stack[-1] if stack else -1
            right = i
            total = prefix[right] - prefix[left + 1]
            result = max(result, nums[popped] * total)
        stack.append(i)

    # drain remaining elements
    while stack:
        popped = stack.pop()
        left = stack[-1] if stack else -1
        right = len(nums)
        total = prefix[right] - prefix[left + 1]
        result = max(result, nums[popped] * total)

    return result % (10**9 + 7)

Enter fullscreen mode Exit fullscreen mode

Mistakes I actually made

Using > instead of >= in the while condition. With just >, equal elements don't get popped. This means when duplicates exist, a later equal element might compute an incorrect left boundary because its twin is still sitting in the stack.

Using the index as the value. I wrote result = max(result, popped * total) where popped is the index I popped from the stack. Should have been nums[popped]. The index is just a position. The value at that position is what you multiply by.

Prefix sum without the leading zero. My first attempt used pref_arr[0] = nums[0], which made the formula for getting sums starting from index 0 a special case. Adding the leading zero makes every range use the same formula: prefix[right] - prefix[left + 1].

What to practice next

These all use the same "for each element, find its boundaries" pattern with a monotonic stack:

  1. Largest Rectangle in Histogram (LeetCode 84). The classic. For each bar, find the widest rectangle where it's the shortest bar. Almost identical logic.
  2. Sum of Subarray Minimums (LeetCode 907). Instead of max(min * sum), you're summing all the min-products. Same boundary finding, different aggregation.
  3. Sum of Subarray Ranges (LeetCode 2104). Find both the min-contribution and max-contribution of each element using two monotonic stacks (one increasing, one decreasing).
  4. Trapping Rain Water (LeetCode 42). Uses a monotonic decreasing stack. When you pop, the boundaries tell you the width and height of water you can trap.
  5. Next Greater Element II (LeetCode 503). Simpler. Good warm-up for understanding the pop mechanics without the prefix sum layer.

I'd recommend doing them in order: 84 first (it's the closest to what we just solved), then 907, then the rest.

I'm building Levelop to help people get better at problems like these. If you want more breakdowns like this, check it out.