BackmediumStackPhonePeAmazon

Shortest Path Cost Engine 6 Solution

Problem Statement

You are tasked with optimizing the energy consumption of a linear processing pipeline. The pipeline is represented by an array heights of length $N$, where each element $h_i$ denotes the processing capacity at position $i$. The total energy cost is determined by the largest rectangular area that can be formed within the histogram defined by these capacities. Specifically, for any contiguous subarray, the cost is the product of its length and the minimum height within that subarray. Your objective is to compute the maximum possible cost across all such contiguous subarrays.

This problem requires identifying the maximum area under the histogram formed by the given array. The optimal solution leverages the Monotonic Stack technique to efficiently determine the span for which each bar is the minimum, thereby calculating the maximum area in linear time. The result represents the peak energy demand that the system must handle to ensure stable operation.

Example 1
Input
heights = [2, 1, 5, 6, 2, 3]
Output
10

Explanation: The histogram bars are [2, 1, 5, 6, 2, 3]. The largest rectangle is formed by the bars of height 5 and 6, which have a width of 2. The area is 5 * 2 = 10. Other candidates include the single bar of height 6 (area 6) and the bar of height 2 spanning the entire width (area 12 is incorrect because the minimum height in the full span is 1, so area is 1*6=6). The bar of height 5 spans indices 2 to 3 (width 2, area 10). The bar of height 6 spans index 3 (width 1, area 6). The bar of height 2 at index 0 spans index 0 (width 1, area 2). The bar of height 1 spans all indices (width 6, area 6). The bar of height 2 at index 4 spans indices 4 to 5 (width 2, area 4). The bar of height 3 spans index 5 (width 1, area 3). The maximum area is 10.

Example 2
Input
heights = [1, 2, 3, 4, 5]
Output
9

Explanation: The histogram is strictly increasing. The largest rectangle is formed by the last two bars (heights 4 and 5) with a minimum height of 4 and width 2, giving an area of 8. Alternatively, the last three bars (3, 4, 5) have a minimum height of 3 and width 3, giving an area of 9. The last four bars (2, 3, 4, 5) have a minimum height of 2 and width 4, giving an area of 8. The last five bars have a minimum height of 1 and width 5, giving an area of 5. The single bar of height 5 has an area of 5. The maximum area is 9.

Example 3
Input
heights = [6, 2, 5, 4, 5, 1, 6]
Output
12

Explanation: The histogram has varying heights. The bar of height 5 at index 2 can extend to index 4 (heights 5, 4, 5) with a minimum height of 4 and width 3, giving an area of 12. The bar of height 6 at index 0 has an area of 6. The bar of height 2 at index 1 spans the entire array (width 7, min height 1, area 7). The bar of height 1 at index 5 spans the entire array (width 7, min height 1, area 7). The bar of height 6 at index 6 has an area of 6. The bar of height 4 at index 3 spans indices 2 to 4 (width 3, min height 4, area 12). The maximum area is 12.

Constraints

  • 1 <= heights.length <= 10^5
  • 0 <= heights[i] <= 10^9
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Shortest Path Cost Engine 6 — Problem Statement & Solution Guide

StackMediumMonotonic Stack Histogram
TimeO(N)
|
SpaceO(N)

Problem Description

You are tasked with optimizing the energy consumption of a linear processing pipeline. The pipeline is represented by an array heights of length $N$, where each element $h_i$ denotes the processing capacity at position $i$. The total energy cost is determined by the largest rectangular area that can be formed within the histogram defined by these capacities. Specifically, for any contiguous subarray, the cost is the product of its length and the minimum height within that subarray. Your objective is to compute the maximum possible cost across all such contiguous subarrays.

This problem requires identifying the maximum area under the histogram formed by the given array. The optimal solution leverages the Monotonic Stack technique to efficiently determine the span for which each bar is the minimum, thereby calculating the maximum area in linear time. The result represents the peak energy demand that the system must handle to ensure stable operation.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Shortest Path Cost Engine 6"

medium

WHY DOES IT MATTER?

The monotonic stack pattern provides a deterministic O(N) solution for problems that require next‑greater or next‑smaller element queries, which appear in many geometry, array, and string challenges. Mastery of this pattern prevents reliance on brute‑force scans that explode on large datasets.

OPTIMIZATION CHALLENGE

The key insight is that a bar's maximal width is bounded by the nearest smaller bar on each side; by postponing area calculation until a smaller bar arrives, we avoid recomputing widths for every possible sub‑array.

REAL-WORLD CONNECTION

Think of a production line where each station's capacity limits the flow of items; the maximal contiguous segment that can sustain a given throughput mirrors the largest rectangle, and the stack acts like a supervisor who records stations until a bottleneck appears.

During an interview, push indices onto the stack only while heights are non‑decreasing; when you encounter a lower height, pop and compute area immediately—this disciplined push/pop order keeps the code clean and bug‑free.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(N)

Core Theory — Why This Approach?

The problem of finding the maximum rectangular area in a histogram is a classic example of a monotonic stack application. Each bar height defines a potential rectangle that can extend left and right until a shorter bar limits its width. A naive scan for every bar would recompute these limits repeatedly, leading to O(N^2) time on large inputs. By maintaining a stack of indices with increasing heights, we can determine, in a single pass, the exact left and right boundaries for each bar when it is popped, thereby computing its maximal area instantly. This approach leverages the fact that once a shorter bar appears, all taller bars to its left can no longer extend beyond that point, allowing us to finalize their contributions.

The optimal paradigm thus transforms the problem into a linear-time sweep combined with a stack that guarantees each element is pushed and popped at most once. This yields O(N) time and O(N) auxiliary space, which scales gracefully even for N up to 10^6. The monotonic stack technique is also reusable for many other range‑query problems, making it a cornerstone pattern in advanced algorithmic toolkits.

Interview Questions on This Problem

Q1How would you adapt the largest rectangle in histogram solution to handle a dynamic array where heights can be updated and queries for the maximum area are interleaved?

Use a segment tree where each node stores the minimum height in its interval and the maximum rectangle area for that interval; updates modify leaf nodes and propagate changes, allowing O(log N) updates and O(log N) queries.

Q2Explain why a simple two‑pointer expansion from each bar fails to achieve linear time, and how the stack avoids redundant work.

Two‑pointer expansion may revisit the same bar many times as left and right pointers move, leading to O(N^2) in the worst case. The stack records bars in increasing order, so each bar is processed exactly once when a smaller height forces its pop, eliminating repeated scans.

Q3In a distributed system processing streaming histogram data, how could you compute the maximum rectangle using the stack approach without storing the entire array?

Maintain a local monotonic stack for each partition of the stream, emit partial results (max area, pending stack state) to a reducer that merges stacks by reconciling heights at partition boundaries, achieving near‑linear processing with bounded memory.

Examples

Example 1

Input

heights = [2, 1, 5, 6, 2, 3]

Output

10

Explanation: The histogram bars are [2, 1, 5, 6, 2, 3]. The largest rectangle is formed by the bars of height 5 and 6, which have a width of 2. The area is 5 * 2 = 10. Other candidates include the single bar of height 6 (area 6) and the bar of height 2 spanning the entire width (area 12 is incorrect because the minimum height in the full span is 1, so area is 1*6=6). The bar of height 5 spans indices 2 to 3 (width 2, area 10). The bar of height 6 spans index 3 (width 1, area 6). The bar of height 2 at index 0 spans index 0 (width 1, area 2). The bar of height 1 spans all indices (width 6, area 6). The bar of height 2 at index 4 spans indices 4 to 5 (width 2, area 4). The bar of height 3 spans index 5 (width 1, area 3). The maximum area is 10.

Example 2

Input

heights = [1, 2, 3, 4, 5]

Output

9

Explanation: The histogram is strictly increasing. The largest rectangle is formed by the last two bars (heights 4 and 5) with a minimum height of 4 and width 2, giving an area of 8. Alternatively, the last three bars (3, 4, 5) have a minimum height of 3 and width 3, giving an area of 9. The last four bars (2, 3, 4, 5) have a minimum height of 2 and width 4, giving an area of 8. The last five bars have a minimum height of 1 and width 5, giving an area of 5. The single bar of height 5 has an area of 5. The maximum area is 9.

Example 3

Input

heights = [6, 2, 5, 4, 5, 1, 6]

Output

12

Explanation: The histogram has varying heights. The bar of height 5 at index 2 can extend to index 4 (heights 5, 4, 5) with a minimum height of 4 and width 3, giving an area of 12. The bar of height 6 at index 0 has an area of 6. The bar of height 2 at index 1 spans the entire array (width 7, min height 1, area 7). The bar of height 1 at index 5 spans the entire array (width 7, min height 1, area 7). The bar of height 6 at index 6 has an area of 6. The bar of height 4 at index 3 spans indices 2 to 4 (width 3, min height 4, area 12). The maximum area is 12.

Constraints

  • 1 <= heights.length <= 10^5
  • 0 <= heights[i] <= 10^9

Optimal Approach & Strategy

Traverse the array once with a monotonic increasing stack; when a lower height appears, pop and compute area using the popped height and the current index as the right boundary.

Brute Force Approach

Check every possible sub‑array, compute the minimum height inside it, and calculate area = minHeight × width; keep the maximum.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(nums) {
   let stack = [];
   let totalCost = 0;
   for (let num of nums) {
       while (stack.length > 0 && stack[stack.length - 1] > num) {
           totalCost += stack.pop();
       }
       stack.push(num);
   }
   while (stack.length > 0) {
       totalCost += stack.pop();
   }
   return totalCost;
}

Asked in Top Tech Interviews

PhonePeAmazon

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.