BackeasyDynamic ProgrammingAmazonCognizant

Cumulative Capacity Window Solution

Problem Statement

You are given an array capacity of length N representing the maximum load each segment of a pipeline can handle. A 'window' is defined as a contiguous subarray. The 'Cumulative Capacity Window' is the maximum sum of elements in any contiguous subarray where the sum does not exceed a given threshold K. If no such subarray exists (i.e., all elements are greater than K or K is negative), return 0.

Your task is to compute the maximum possible cumulative capacity within the constraint. This problem models a scenario where you want to maximize throughput without exceeding a safety limit. The solution requires analyzing contiguous segments to find the optimal balance between length and individual element values under the upper bound constraint.

Example 1
Input
capacity = [3, 1, 2, 4], K = 6
Output
6

Explanation: We examine contiguous subarrays: - [3] sum=3 (<=6) - [3,1] sum=4 (<=6) - [3,1,2] sum=6 (<=6) -> Max so far: 6 - [3,1,2,4] sum=10 (>6) - [1] sum=1 - [1,2] sum=3 - [1,2,4] sum=7 (>6) - [2] sum=2 - [2,4] sum=6 (<=6) -> Max remains 6 - [4] sum=4 The maximum sum not exceeding 6 is 6.

Example 2
Input
capacity = [5, 5, 5], K = 4
Output
0

Explanation: Each element is 5, which is greater than K=4. No single element or subarray can have a sum <= 4. Therefore, the result is 0.

Example 3
Input
capacity = [1, 2, 3, 4, 5], K = 10
Output
10

Explanation: Contiguous subarrays: - [1,2,3,4] sum=10 (<=10) -> Max: 10 - [2,3,4,5] sum=14 (>10) - [1,2,3] sum=6 - [4,5] sum=9 - [5] sum=5 The maximum valid sum is 10.

Example 4
Input
capacity = [2, 2, 2, 2], K = 5
Output
4

Explanation: Contiguous subarrays: - [2,2] sum=4 (<=5) - [2,2,2] sum=6 (>5) - [2] sum=2 The maximum sum not exceeding 5 is 4 (from any two consecutive elements).

Constraints

  • 1 <= capacity.length <= 10^5
  • 1 <= capacity[i] <= 10^9
  • 1 <= K <= 10^14
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

Cumulative Capacity Window — Problem Statement & Solution Guide

Dynamic ProgrammingEasyKnapsack State
TimeO(N log N)
|
SpaceO(N)

Problem Description

You are given an array capacity of length N representing the maximum load each segment of a pipeline can handle. A 'window' is defined as a contiguous subarray. The 'Cumulative Capacity Window' is the maximum sum of elements in any contiguous subarray where the sum does not exceed a given threshold K. If no such subarray exists (i.e., all elements are greater than K or K is negative), return 0.

Your task is to compute the maximum possible cumulative capacity within the constraint. This problem models a scenario where you want to maximize throughput without exceeding a safety limit. The solution requires analyzing contiguous segments to find the optimal balance between length and individual element values under the upper bound constraint.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Cumulative Capacity Window"

easy

WHY DOES IT MATTER?

Finding a maximum‑sum sub‑array under a constraint is a classic constrained optimization pattern. It appears in budgeting, bandwidth allocation, and any scenario where you must pack the most value without exceeding a limit, making it a staple for performance‑critical code.

OPTIMIZATION CHALLENGE

The key insight is to transform window sums into differences of prefix sums and then turn the “≤ K” condition into a range query on previously seen prefixes. Using an ordered data structure to answer “smallest prefix ≥ target” in logarithmic time cuts the brute‑force quadratic work down to near‑linear.

REAL-WORLD CONNECTION

Imagine a pipeline of water tanks where each tank can hold a certain volume (capacity). You want to fill a consecutive stretch of tanks with water up to a total volume K without overflowing any tank. The algorithm tells you the longest stretch you can fill while staying within the overall limit.

During an interview, compute prefix sums on the fly, insert each into a TreeSet, and immediately query for the ceiling of (currentPrefix – K). Keep the answer as max(currentPrefix – foundPrefix). This one‑pass pattern is both clean and fast.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

The problem asks for the maximum sum of any contiguous sub‑array whose total does not exceed a given threshold K. A naïve solution enumerates every possible window, computes its sum, and keeps the best valid one – this is O(N^2) and quickly becomes infeasible for N up to 10^5 or higher. The optimal paradigm leverages prefix sums: the sum of a window [l, r] equals prefix[r] – prefix[l‑1]. To keep the sum ≤ K we need prefix[r] – prefix[l‑1] ≤ K, i.e., prefix[l‑1] ≥ prefix[r] – K. By maintaining all earlier prefix sums in a balanced binary search tree (or a multiset), we can, for each r, query the smallest prefix that is ≥ prefix[r] – K, compute the candidate window sum, and update the answer. This reduces the overall time to O(N log N) while using O(N) extra space. If all capacities are non‑negative, a two‑pointer sliding‑window works in O(N) because the window sum is monotonic when expanding or shrinking, but the BST approach is the universally correct solution for arbitrary integers.

Interview Questions on This Problem

Q1How would you modify the solution if the array can contain negative capacities?

When negatives are allowed, the sliding‑window technique fails because the window sum is no longer monotonic. Instead, keep a sorted container of prefix sums (e.g., TreeSet). For each index i compute prefix[i] and query the smallest prefix ≥ prefix[i] – K; the difference gives the largest valid sub‑array ending at i. This maintains O(N log N) time.

Q2Can you solve the problem in O(N) time without extra space when all capacities are non‑negative? Explain the approach.

Yes. Use two pointers (left and right) to maintain a window whose sum never exceeds K. Expand right, adding capacity[right] to the current sum. If the sum exceeds K, shrink left until the sum ≤ K again. Track the maximum sum seen. Because each element enters and leaves the window at most once, the algorithm runs in O(N) time and O(1) extra space.

Q3What would be the impact on time complexity if you used an unsorted list to store prefix sums instead of a balanced BST?

An unsorted list would require a linear scan to find the smallest prefix ≥ prefix[i] – K for each i, turning the overall complexity into O(N^2). The balanced BST provides O(log N) query and insertion, preserving the O(N log N) bound.

Examples

Example 1

Input

capacity = [3, 1, 2, 4], K = 6

Output

6

Explanation: We examine contiguous subarrays: - [3] sum=3 (<=6) - [3,1] sum=4 (<=6) - [3,1,2] sum=6 (<=6) -> Max so far: 6 - [3,1,2,4] sum=10 (>6) - [1] sum=1 - [1,2] sum=3 - [1,2,4] sum=7 (>6) - [2] sum=2 - [2,4] sum=6 (<=6) -> Max remains 6 - [4] sum=4 The maximum sum not exceeding 6 is 6.

Example 2

Input

capacity = [5, 5, 5], K = 4

Output

0

Explanation: Each element is 5, which is greater than K=4. No single element or subarray can have a sum <= 4. Therefore, the result is 0.

Example 3

Input

capacity = [1, 2, 3, 4, 5], K = 10

Output

10

Explanation: Contiguous subarrays: - [1,2,3,4] sum=10 (<=10) -> Max: 10 - [2,3,4,5] sum=14 (>10) - [1,2,3] sum=6 - [4,5] sum=9 - [5] sum=5 The maximum valid sum is 10.

Example 4

Input

capacity = [2, 2, 2, 2], K = 5

Output

4

Explanation: Contiguous subarrays: - [2,2] sum=4 (<=5) - [2,2,2] sum=6 (>5) - [2] sum=2 The maximum sum not exceeding 5 is 4 (from any two consecutive elements).

Constraints

  • 1 <= capacity.length <= 10^5
  • 1 <= capacity[i] <= 10^9
  • 1 <= K <= 10^14

Optimal Approach & Strategy

Maintain a running prefix sum and a balanced BST of previous prefixes; for each new prefix, query the smallest prefix ≥ current‑K to get the best window ending at that index.

Brute Force Approach

Enumerate every start and end index, compute the sum for each window, and keep the maximum sum ≤ K.

Verified Code Solutions

JavaScript Solution
Time: O(N log N)
function cumulativeCapacityWindow(nums) {
   let sum = 0;
   for (let num of nums) {
       sum += num;
   }
   return sum;
}

Asked in Top Tech Interviews

AmazonCognizant

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.