BackeasyBinary SearchGoogleAmazon

Protocol Tome Consolidator 12 Solution

Problem Statement

You are given an integer array nums and a positive integer K. Your task is to determine the greatest possible sum of any contiguous sub‑array that contains exactly K elements. The input consists of the size of the array, the value K, and the sequence of integers. Output the maximum sum achievable. The solution must run efficiently for large inputs.

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

Explanation: All sub‑arrays of length 3 are: [1,2,-1] (sum=2), [2,-1,4] (sum=5), [-1,4,5] (sum=8). The largest sum among them is 8.

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

Explanation: The sums of every 2‑element window are: -3+-2=-5, -2+-5=-7, -5+-1=-6, -1+-4=-5, -4+-6=-10. The maximum (least negative) sum is -5.

Example 3
Input
8 4 10 -2 3 5 -1 6 2 4
Output
16

Explanation: Sliding a window of size 4 yields sums: 10-2+3+5=16, -2+3+5-1=5, 3+5-1+6=13, 5-1+6+2=12, -1+6+2+4=11. The highest sum is 16.

Constraints

  • 1 <= nums.length <= 100000
  • 1 <= K <= nums.length
  • -10^9 <= nums[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

Protocol Tome Consolidator 12 — Problem Statement & Solution Guide

Binary SearchEasyFixed/Dynamic Window
TimeO(N)
|
SpaceO(1)

Problem Description

You are given an integer array nums and a positive integer K. Your task is to determine the greatest possible sum of any contiguous sub‑array that contains exactly K elements. The input consists of the size of the array, the value K, and the sequence of integers. Output the maximum sum achievable. The solution must run efficiently for large inputs.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Protocol Tome Consolidator 12"

easy

WHY DOES IT MATTER?

Fixed‑size sliding windows are a cornerstone for many linear‑time array problems.

OPTIMIZATION CHALLENGE

Transforming an O(N·K) brute force into O(N) hinges on reusing overlapping computation.

REAL-WORLD CONNECTION

They model real‑time data streams like monitoring the last K sensor readings for anomaly detection.

Initialize the first window once, then reuse its sum; avoid recomputing from scratch inside the loop.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

The naive solution enumerates every possible sub‑array of length K, summing each in O(K) time, which leads to O(N·K) overall and quickly becomes infeasible for N up to 10^5 or more. This approach also repeats work because adjacent windows share K‑1 elements, causing unnecessary recomputation.

The optimal paradigm is the sliding‑window technique: compute the sum of the first K elements once, then slide the window one position at a time, subtracting the element exiting the window and adding the new entrant. This yields a linear O(N) traversal with O(1) auxiliary space, guaranteeing scalability for large inputs while preserving exact‑K length constraints.

Interview Questions on This Problem

Q1How does the sliding‑window method avoid recomputing sums for overlapping sub‑arrays?

It updates the current sum by subtracting the element that leaves the window and adding the new element that enters. This constant‑time update eliminates the O(K) recomputation for each shift.

Q2What edge case must you handle when K is larger than the array length?

If K > N the problem is undefined; a robust solution should return an error value or zero. Validating this condition up front prevents out‑of‑bounds access.

Q3Can the algorithm handle negative numbers, and does it affect the max‑sum logic?

Yes, the window sum may become negative, but the algorithm still tracks the maximum encountered sum. No special case is needed beyond initializing the max with the first window sum.

Examples

Example 1

Input

5 3
1 2 -1 4 5

Output

8

Explanation: All sub‑arrays of length 3 are: [1,2,-1] (sum=2), [2,-1,4] (sum=5), [-1,4,5] (sum=8). The largest sum among them is 8.

Example 2

Input

6 2
-3 -2 -5 -1 -4 -6

Output

-5

Explanation: The sums of every 2‑element window are: -3+-2=-5, -2+-5=-7, -5+-1=-6, -1+-4=-5, -4+-6=-10. The maximum (least negative) sum is -5.

Example 3

Input

8 4
10 -2 3 5 -1 6 2 4

Output

16

Explanation: Sliding a window of size 4 yields sums: 10-2+3+5=16, -2+3+5-1=5, 3+5-1+6=13, 5-1+6+2=12, -1+6+2+4=11. The highest sum is 16.

Constraints

  • 1 <= nums.length <= 100000
  • 1 <= K <= nums.length
  • -10^9 <= nums[i] <= 10^9

Optimal Approach & Strategy

Use a sliding window: compute the first K‑element sum, then slide, updating the sum in O(1) per step while tracking the max.

Brute Force Approach

Iterate over every possible start index, sum K elements for each window, and keep the maximum.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(nums, K) {
    nums.sort((a, b) => b - a);
    let max_sum = -Infinity;
    for (let i = 0; i <= nums.length - K; i++) {
      let current_sum = 0;
      for (let j = i; j < i + K; j++) {
        current_sum += nums[j];
      }
      max_sum = Math.max(max_sum, current_sum);
    }
    return max_sum;
}

Asked in Top Tech Interviews

GoogleAmazonMicrosoft

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.