BackeasyDynamic ProgrammingCognizantPhonePe

Bounded Range Segment Calculator 8 Solution

Problem Statement

You are given an integer array nums of length n and an integer k (1 ≤ k ≤ n). Your task is to find the maximum possible sum of any contiguous subarray whose length does not exceed k. The subarray may contain a single element or up to k elements. If all numbers are negative, the answer is the largest (least negative) single element. The input consists of two lines: the first line contains n and k, and the second line contains the n space‑separated integers of nums. Output a single integer – the maximum achievable sum.

The problem is a classic bounded‑length maximum subarray problem. A straightforward solution uses a sliding window of size at most k to maintain the sum of the current window and updates the maximum sum as the window slides. The algorithm runs in O(n) time and uses O(1) extra space.

The goal is to implement this algorithm efficiently and correctly for the given constraints.

Example 1
Input
5 3 1 -2 3 4 -5
Output
7

Explanation: All possible contiguous subarrays of length up to 3 are examined. The subarray [3,4] has sum 7, which is the largest. No longer subarray yields a higher sum, so the answer is 7.

Example 2
Input
4 2 -1 -2 -3 -4
Output
-1

Explanation: All numbers are negative. The best choice is the single element -1, which is the maximum among all subarrays of length 1 or 2.

Example 3
Input
5 4 5 -1 5 -1 5
Output
9

Explanation: The subarray [5,-1,5] (or its symmetric counterpart) has sum 9, which is the highest among all subarrays of length up to 4.

Example 4
Input
3 2 1000000000 -1000000000 1000000000
Output
1000000000

Explanation: The single element 1000000000 is the maximum sum. Any subarray of length 2 sums to 0, which is smaller.

Constraints

  • 1 <= n <= 100000
  • 1 <= k <= n
  • -1000000000 <= nums[i] <= 1000000000
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 Calculator 8 — Problem Statement & Solution Guide

Dynamic ProgrammingEasyKnapsack State Optimization
TimeO(n)
|
SpaceO(k)

Problem Description

You are given an integer array nums of length n and an integer k (1 ≤ k ≤ n). Your task is to find the maximum possible sum of any contiguous subarray whose length does not exceed k. The subarray may contain a single element or up to k elements. If all numbers are negative, the answer is the largest (least negative) single element. The input consists of two lines: the first line contains n and k, and the second line contains the n space‑separated integers of nums. Output a single integer – the maximum achievable sum.

The problem is a classic bounded‑length maximum subarray problem. A straightforward solution uses a sliding window of size at most k to maintain the sum of the current window and updates the maximum sum as the window slides. The algorithm runs in O(n) time and uses O(1) extra space.

The goal is to implement this algorithm efficiently and correctly for the given constraints.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Bounded Range Segment Calculator 8"

easy

WHY DOES IT MATTER?

This pattern is essential for solving problems involving sliding windows with constraints on the window size, particularly when optimizing for maximum or minimum values. It is a fundamental technique in dynamic programming and greedy algorithms, often appearing in problems related to stock trading, resource allocation, and signal processing.

OPTIMIZATION CHALLENGE

The key insight is to avoid recalculating the sum or minimum for each window from scratch. By using a monotonic deque, we maintain the minimum prefix sum in the valid range in amortized O(1) time per element, reducing the overall complexity from $O(n \cdot k)$ to $O(n)$.

REAL-WORLD CONNECTION

In distributed systems, this pattern is analogous to maintaining a sliding window of recent events or metrics for real-time monitoring. For example, calculating the maximum load on a server cluster over the last $k$ minutes, where you need to efficiently update the maximum as new data points arrive and old ones expire.

In an interview, clearly state that you are using a prefix sum array to convert the subarray sum problem into a difference of prefix sums. Then, explain that you need to find the minimum prefix sum in a sliding window of size $k$, which is a classic application of a monotonic deque. This shows a deep understanding of both the problem transformation and the data structure choice.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(k)

Core Theory — Why This Approach?

The problem of finding the maximum sum of a contiguous subarray with a length constraint is a classic application of the Sliding Window technique combined with prefix sums or dynamic programming. While the unconstrained maximum subarray problem (Kadane's Algorithm) runs in O(n), adding a length constraint $k$ requires tracking the sum of the last $k$ elements efficiently. A naive approach that recalculates the sum for every possible subarray of length up to $k$ results in $O(n \cdot k)$ time complexity, which is suboptimal for large $n$ and $k$.

The optimal paradigm leverages the fact that the sum of a subarray ending at index $i$ with length $L$ can be derived from the sum of the subarray ending at $i-1$ with length $L-1$ plus $nums[i]$. However, a more direct and efficient approach uses a sliding window of size $k$. We maintain a window sum that represents the sum of the last $k$ elements. As we iterate through the array, we add the current element to the window sum and subtract the element that falls out of the window (if the window size exceeds $k$). To find the maximum sum of *any* subarray of length $\le k$, we must consider that the maximum might occur at a window smaller than $k$. Therefore, we track the maximum sum encountered by any valid window. A robust DP formulation defines $dp[i]$ as the maximum sum of a subarray ending at index $i$ with length $\le k$. The transition is $dp[i] = \max(nums[i], dp[i-1] + nums[i])$ if the length constraint allows extending the previous subarray, but we must ensure the length does not exceed $k$. A simpler and often preferred O(n) solution uses a prefix sum array $P$ where $P[i]$ is the sum of the first $i$ elements. The sum of subarray from $j$ to $i$ is $P[i+1] - P[j]$. We need to maximize $P[i+1] - P[j]$ subject to $i - j + 1 \le k$, which implies $j \ge i - k + 1$. Thus, for each $i$, we need the minimum $P[j]$ in the range $[i-k+1, i]$. This can be solved in O(n) using a monotonic deque or simply by observing that if we just want the max sum of *any* subarray of length exactly $k$ or less, we can iterate and maintain the current window sum, but we must also check smaller windows. Actually, the most efficient O(n) approach for 'max sum of subarray with length <= k' is to use a prefix sum and a monotonic queue to find the minimum prefix sum in the valid range for each end index. However, for an 'easy' difficulty, a simpler O(n*k) might be accepted, but the optimal is O(n). Let's refine: The problem asks for max sum of *any* contiguous subarray with length $\le k$. This is equivalent to finding the maximum difference $P[i] - P[j]$ where $i > j$ and $i - j \le k$. This is a standard problem solvable in O(n) using a monotonic deque to maintain the minimum prefix sum in the sliding window of indices.

Why naive approaches fail: An $O(n^2)$ or $O(n \cdot k)$ approach iterates over all starting points and all possible lengths up to $k$. For $n=10^5$ and $k=10^5$, this is $10^{10}$ operations, which is too slow. The optimal O(n) approach using a monotonic deque ensures that each element is added and removed from the deque at most once, leading to linear time complexity. This is crucial for handling large input sizes typical in production environments and competitive programming.

Interview Questions on This Problem

Q1How would you modify your solution if the array contained only positive numbers? Would the complexity change?

If all numbers are positive, the maximum sum subarray of length $\le k$ will always be the subarray of length exactly $k$ (or the entire array if $n < k$). This is because adding any positive number increases the sum. In this specific case, you can simply slide a window of size $k$ and find the maximum window sum in O(n) time without needing a monotonic deque, as the 'minimum prefix sum' logic simplifies to just checking the fixed-size window sums. However, the general O(n) solution with the deque still works and is robust.

Q2What is the time and space complexity of your solution, and how does it compare to a brute-force approach?

The brute-force approach has a time complexity of $O(n \cdot k)$ and space complexity of $O(1)$. The optimized approach using a monotonic deque has a time complexity of $O(n)$ and space complexity of $O(k)$ for the deque (or $O(n)$ in the worst case, but typically bounded by $k$). The space complexity is $O(k)$ because the deque only stores indices within the current window of size $k$. This is a significant improvement for large $k$.

Q3Can you explain how the monotonic deque helps in finding the minimum prefix sum in the sliding window?

The monotonic deque maintains indices of the prefix sum array such that the corresponding prefix sums are in increasing order. When we add a new index $i$, we remove from the back of the deque any indices $j$ where $P[j] \ge P[i]$, because $i$ is a better candidate for the minimum (it has a smaller or equal value and a larger index, so it will stay in the window longer). The front of the deque always holds the index with the minimum prefix sum in the current valid window $[i-k+1, i]$. We also remove from the front any indices that are out of the window range ($j < i-k+1$). This ensures that the front of the deque always gives the minimum $P[j]$ for the current $i$.

Examples

Example 1

Input

5 3
1 -2 3 4 -5

Output

7

Explanation: All possible contiguous subarrays of length up to 3 are examined. The subarray [3,4] has sum 7, which is the largest. No longer subarray yields a higher sum, so the answer is 7.

Example 2

Input

4 2
-1 -2 -3 -4

Output

-1

Explanation: All numbers are negative. The best choice is the single element -1, which is the maximum among all subarrays of length 1 or 2.

Example 3

Input

5 4
5 -1 5 -1 5

Output

9

Explanation: The subarray [5,-1,5] (or its symmetric counterpart) has sum 9, which is the highest among all subarrays of length up to 4.

Example 4

Input

3 2
1000000000 -1000000000 1000000000

Output

1000000000

Explanation: The single element 1000000000 is the maximum sum. Any subarray of length 2 sums to 0, which is smaller.

Constraints

  • 1 <= n <= 100000
  • 1 <= k <= n
  • -1000000000 <= nums[i] <= 1000000000

Optimal Approach & Strategy

Use a prefix sum array to represent the sum of elements up to each index. Then, use a monotonic deque to maintain the minimum prefix sum in a sliding window of size $k$ as you iterate through the array. For each index $i$, the maximum sum ending at $i$ is $P[i] - \min(P[j])$ for $j$ in $[i-k+1, i]$, which can be found in O(1) amortized time using the deque.

Brute Force Approach

Iterate over all possible starting indices and for each start, iterate over all possible lengths up to $k$, calculating the sum of each subarray and keeping track of the maximum sum encountered. This approach has a time complexity of $O(n \cdot k)$ and is inefficient for large inputs.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function solution(nums, k) {
   let maxSum = 0;
   let currentSum = 0;
   for (let i = 0; i < nums.length; i++) {
       currentSum += nums[i];
       if (currentSum > k) {
           currentSum = nums[i];
       } else if (currentSum === k) {
           maxSum = Math.max(maxSum, currentSum);
           currentSum = 0;
       }
   }
   return maxSum;
}

Asked in Top Tech Interviews

CognizantPhonePe

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.