BackhardTwo PointersMicrosoftApple

Bounded Range Segment Evaluator 8 Solution

Problem Statement

You are tasked with optimizing the throughput of a dual-channel data pipeline. The system is represented by an array heights of length N, where each element heights[i] denotes the maximum capacity limit of the i-th processing node. The pipeline operates by selecting two distinct nodes, i and j (where i < j), to form a bounded range segment. The effective throughput of this segment is determined by the minimum of the two node capacities, min(heights[i], heights[j]), multiplied by the distance between them, j - i. Your objective is to identify the pair of nodes that yields the maximum possible throughput. Return this maximum value. If no valid pair exists (i.e., N < 2), return 0.

Example 1
Input
heights = [1, 8, 6, 2, 5, 4, 8, 3, 7]
Output
49

Explanation: We evaluate pairs to maximize min(heights[i], heights[j]) * (j - i). The optimal pair is indices 1 and 6 (values 8 and 8). The calculation is min(8, 8) * (6 - 1) = 8 * 5 = 40. Wait, let's re-evaluate. Indices 0 and 8: min(1,7)*8 = 8. Indices 1 and 8: min(8,7)*7 = 49. Indices 2 and 8: min(6,7)*6 = 36. Indices 1 and 6: min(8,8)*5 = 40. The maximum is 49 from indices 1 and 8.

Example 2
Input
heights = [1, 1]
Output
1

Explanation: There is only one pair: indices 0 and 1. The calculation is min(1, 1) * (1 - 0) = 1 * 1 = 1.

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

Explanation: We check pairs. Indices 0 and 4: min(4, 4) * (4 - 0) = 4 * 4 = 16. Indices 0 and 1: min(4, 3) * 1 = 3. Indices 1 and 4: min(3, 4) * 3 = 9. The maximum value is 16.

Example 4
Input
heights = [5, 5, 5, 5, 5]
Output
20

Explanation: All values are 5. The maximum distance is between index 0 and 4. Calculation: min(5, 5) * (4 - 0) = 5 * 4 = 20.

Constraints

  • 2 <= heights.length <= 10^5
  • 1 <= heights[i] <= 10^4
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

Bounded Range Segment Evaluator 8 — Problem Statement & Solution Guide

Two PointersHardContainer With Most Water
TimeO(N)
|
SpaceO(1)

Problem Description

You are tasked with optimizing the throughput of a dual-channel data pipeline. The system is represented by an array heights of length N, where each element heights[i] denotes the maximum capacity limit of the i-th processing node. The pipeline operates by selecting two distinct nodes, i and j (where i < j), to form a bounded range segment. The effective throughput of this segment is determined by the minimum of the two node capacities, min(heights[i], heights[j]), multiplied by the distance between them, j - i. Your objective is to identify the pair of nodes that yields the maximum possible throughput. Return this maximum value. If no valid pair exists (i.e., N < 2), return 0.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Bounded Range Segment Evaluator 8"

hard

WHY DOES IT MATTER?

Two‑pointer linear scans turn quadratic pairwise problems into O(N) solutions, a critical skill for scaling algorithms in high‑throughput systems where input sizes can be massive.

OPTIMIZATION CHALLENGE

The key insight is recognizing that the limiting factor is the smaller height; discarding it safely reduces the search space without losing the optimal solution, collapsing the double loop into a single linear pass.

REAL-WORLD CONNECTION

Think of a water pipeline with two valves at opposite ends; the flow is limited by the narrower valve. To maximize flow you slide the valve with the smaller opening inward, seeking a wider section, mirroring how the algorithm narrows the search space.

During an interview, write the two‑pointer loop first, then add the max‑area update and the pointer‑move condition. Keep the code tight—no extra arrays—so you can discuss O(1) space and avoid off‑by‑one bugs.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

The problem is a classic two‑pointer maximization scenario often illustrated by the "Container With Most Water" model. The naive view treats each pair (i, j) independently, computing the area (j‑i) * min(heights[i], heights[j]) and keeping the maximum, which leads to O(N²) time and quickly becomes infeasible for N up to 10⁵ or more. The optimal paradigm leverages the monotonic property of the limiting height: moving the pointer at the shorter side inward can only potentially increase the area because the width shrinks while the height may grow, whereas moving the taller side cannot improve the result for the current pair. By iteratively discarding the sub‑optimal side, we guarantee that every pair is examined at most once, achieving linear time.

The two‑pointer technique is essentially a greedy sweep from both ends of the array. At each step we compute the current throughput, update the global maximum, and then advance the pointer that points to the smaller capacity. This works because any future segment that includes the larger height but excludes the smaller one cannot surpass the current best unless the smaller height is replaced by a taller one. Hence the algorithm converges to the optimal bounded range without revisiting discarded pairs, delivering O(N) time and O(1) extra space.

Interview Questions on This Problem

Q1How does the two‑pointer approach guarantee that we never miss the optimal pair in the Container With Most Water problem?

Because the area is limited by the shorter of the two heights, moving the taller pointer inward cannot increase the area for the current width; only moving the shorter pointer can potentially find a taller height that compensates for the reduced width. This greedy elimination ensures every viable candidate is considered.

Q2Can you modify the algorithm to also return the indices of the optimal segment, not just its maximum throughput?

Yes. Maintain two variables bestLeft and bestRight that store the current i and j whenever a new maximum area is found. The two‑pointer loop updates these variables alongside the max area, and after the loop they contain the optimal indices.

Q3If the heights array can contain negative values (representing reverse flow), does the two‑pointer strategy still work?

No. The original proof relies on heights being non‑negative, as the area is defined by width times the minimum height. With negative values the notion of "minimum" no longer bounds the area, and the greedy discard rule fails; a full O(N²) scan or a different DP/segment‑tree approach would be needed.

Examples

Example 1

Input

heights = [1, 8, 6, 2, 5, 4, 8, 3, 7]

Output

49

Explanation: We evaluate pairs to maximize min(heights[i], heights[j]) * (j - i). The optimal pair is indices 1 and 6 (values 8 and 8). The calculation is min(8, 8) * (6 - 1) = 8 * 5 = 40. Wait, let's re-evaluate. Indices 0 and 8: min(1,7)*8 = 8. Indices 1 and 8: min(8,7)*7 = 49. Indices 2 and 8: min(6,7)*6 = 36. Indices 1 and 6: min(8,8)*5 = 40. The maximum is 49 from indices 1 and 8.

Example 2

Input

heights = [1, 1]

Output

1

Explanation: There is only one pair: indices 0 and 1. The calculation is min(1, 1) * (1 - 0) = 1 * 1 = 1.

Example 3

Input

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

Output

16

Explanation: We check pairs. Indices 0 and 4: min(4, 4) * (4 - 0) = 4 * 4 = 16. Indices 0 and 1: min(4, 3) * 1 = 3. Indices 1 and 4: min(3, 4) * 3 = 9. The maximum value is 16.

Example 4

Input

heights = [5, 5, 5, 5, 5]

Output

20

Explanation: All values are 5. The maximum distance is between index 0 and 4. Calculation: min(5, 5) * (4 - 0) = 5 * 4 = 20.

Constraints

  • 2 <= heights.length <= 10^5
  • 1 <= heights[i] <= 10^4

Optimal Approach & Strategy

Initialize two pointers at the array ends, compute area, move the pointer at the smaller height inward, and repeat until the pointers meet, tracking the maximum area.

Brute Force Approach

Check every possible pair (i, j), compute (j‑i) * min(heights[i], heights[j]), and keep the maximum.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(nums) {
   let left = 0;
   let right = nums.length - 1;
   let maxSum = 0;
   let sum = 0;
   let minVal = Infinity;
   while (left <= right) {
       if (nums[left] < nums[right]) {
           sum = nums[left] * (right - left + 1);
           minVal = Math.min(minVal, nums[left]);
           maxSum += sum;
           left++;
       } else {
           sum = nums[right] * (right - left + 1);
           minVal = Math.min(minVal, nums[right]);
           maxSum += sum;
           right--;
       }
   }
   return maxSum;
}

Asked in Top Tech Interviews

MicrosoftApple

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.