Largest Sum of K Consecutive Elements: Sliding Window in JS

Finding the Largest Sum of Consecutive Elements | Javascript

Meera, a second-year engineering student in Kochi, helps at her family's kirana store on weekends. One evening her father hands her a notebook with ten days of sales, in thousands of rupees: 1, 2, 3, 4, 3, 5, 4, 6, 7, 8. "Which four days in a row brought in the most money?" he asks. Meera has just started Data Structures and Algorithms (DSA), so she puts the numbers in an array, writes two nested loops, and gets 25. Her father is happy. Her DSA tutor is not done yet: what if it were three years of daily sales, or a week where every day was a loss? That is the real question behind this classic interview problem: how do you find the largest sum of k consecutive elements in an array, correctly and fast?

This post solves the problem twice. First with a simple nested-loop (brute force) solution, where we will also find a small bug that hides in many versions of it. Then with the sliding window technique, which does the same job in a single pass. At the end we look briefly at Kadane's algorithm, which solves the related "any length" version of the problem.

The Problem in Plain Words

We are given an array of numbers and a window size k. We must find the largest total of k numbers that sit next to each other in the array. Here is the example we will use throughout:

const arr = [1, 2, 3, 4, 3, 5, 4, 6, 7, 8];
const k = 4;

The key word is consecutive. You cannot pick any four numbers you like; they must be a continuous block. With 10 numbers and a window of 4, there are exactly 7 such blocks (in general, arr.length - k + 1 of them):

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

A group like [1, 4, 6, 8] is not allowed, because those numbers are not next to each other in the array. Also note that this is a different question from "what is the largest element". The largest element here is 8, but the largest sum of four neighbours is 4 + 6 + 7 + 8 = 25.

Where You Meet This in Real Life

The question Meera's father asked is exactly this problem, with k = 4: the numbers are daily sales, and he wants the best 4-day stretch. Once you see it that way, the same pattern turns up in many places:

  • The busiest 7 days of website traffic in a month.
  • The hottest 3-day spell in a year of temperature readings.
  • The best 5-day run of a share price or a mutual fund NAV.
  • The peak hour (60 one-minute counts) of UPI payments or food delivery orders.

Approach 1: Brute Force (Nested Loops)

The most direct idea is to check every window, add up its numbers, and remember the biggest total. This is how most people first write it:

function sol(arr, n) {
  if (n > arr.length) {
    return "num should be less than arr.length";
  }

  let result = 0;
  for (let i = 0; i < arr.length - n + 1; i++) {
    let tmp = 0;
    for (let j = 0; j < n; j++) {
      tmp += arr[i + j];
    }
    if (tmp > result) {
      result = tmp;
    }
  }
  return result;
}

console.log(sol([1, 2, 3, 4, 3, 5, 4, 6, 7, 8], 4)); // 25

Let's walk through what each part does before we fix it.

Step by Step

The input check. If the window is bigger than the array (say 5 numbers wanted from an array of 3), there is no valid answer, so the function stops early. This idea is right, but returning a sentence as text is a problem, as we will see in the edge-cases section.

The "champion" variable. result holds the best sum found so far. Every time a window beats it, the champion is replaced. This is also where the bug lives.

The outer loop picks the starting position i of each window. It stops at arr.length - n, because a window starting any later would run past the end of the array. For our example that means i goes from 0 to 6, which gives the 7 windows listed above.

The inner loop adds up the n numbers of the current window into tmp, which starts fresh at 0 for every window. For the first window it builds up 1, 3, 6 and finally 10.

Here is every window the function checks, and how the champion changes:

Start iWindowSumBest so far
0[1, 2, 3, 4]1010
1[2, 3, 4, 3]1212
2[3, 4, 3, 5]1515
3[4, 3, 5, 4]1616
4[3, 5, 4, 6]1818
5[5, 4, 6, 7]2222
6[4, 6, 7, 8]2525

The Hidden Bug: All-Negative Arrays

The function starts the champion at 0. That quietly assumes at least one window will have a positive sum. Give it an array where every number is negative, and no window can ever beat 0:

console.log(sol([-1, -2, -3, -4], 2)); // 0  ← wrong, no window adds up to 0

The correct answer is -3, from the window [-1, -2]. Losses, temperature changes and price movements are often negative, so this is not just a textbook case. The fix is to start the champion at -Infinity, a special JavaScript value that is smaller than every real number, so the first window always replaces it.

Meera runs into this the next weekend. During a slow week her father records the daily profit as losses, -1, -2, -3 and -4 (in thousands), and asks which two days in a row lost the least. Her function prints 0, a number that is not the sum of any two days. Starting the champion at -Infinity instead gives -3, the first two days, which is the right answer.

Here is the corrected brute force. It also uses clearer names, returns null for bad input, and rejects window sizes that are zero, negative or not whole numbers:

function maxSumBrute(arr, k) {
  if (!Number.isInteger(k) || k <= 0 || k > arr.length) return null;

  let best = -Infinity; // not 0!
  for (let start = 0; start <= arr.length - k; start++) {
    let windowSum = 0;
    for (let j = 0; j < k; j++) {
      windowSum += arr[start + j];
    }
    if (windowSum > best) best = windowSum;
  }
  return best;
}

console.log(maxSumBrute([1, 2, 3, 4, 3, 5, 4, 6, 7, 8], 4)); // 25
console.log(maxSumBrute([-1, -2, -3, -4], 2));             // -3

Why the Brute Force Gets Slow

Look at the first two windows side by side. Window 1 adds 1 + 2 + 3 + 4, and window 2 adds 2 + 3 + 4 + 3. The middle part, 2 + 3 + 4, is added all over again. With a window of 4 this waste is small, but with a window of 1,000 the function re-adds 999 numbers it has just added.

In numbers: there are n - k + 1 windows and each one costs k additions. So the work is about n × k, written O(n·k). For an array of 1,00,000 numbers and a window of 1,000, that is 9,90,01,000 additions (about 9.9 crore). Many tutorials (including the earlier version of this post) call this O(n²). That is only the worst case, when k is around half of n; for a small fixed window like 7 days it behaves almost like a single pass.

Approach 2: The Sliding Window

Here is the trick. When the window moves one step to the right, only two numbers change: one number leaves on the left, and one new number enters on the right. Everything in the middle stays the same. So instead of adding the whole window again, we take the old sum, subtract the number that left, and add the number that came in.

Window 1 sum = 10 Window 2 sum = 12 1234354678 1234354678 leaves (−1) enters (+3) New sum = 10 − 1 + 3 = 12 (one subtraction, one addition)

No matter how wide the window is, each step now costs one subtraction and one addition. Here is the full function:

function maxSumWindow(arr, k) {
  if (!Number.isInteger(k) || k <= 0 || k > arr.length) return null;

  // 1. Add up the first window once
  let windowSum = 0;
  for (let i = 0; i < k; i++) {
    windowSum += arr[i];
  }

  // 2. Slide: add the new right element, drop the old left one
  let best = windowSum;
  for (let i = k; i < arr.length; i++) {
    windowSum += arr[i] - arr[i - k];
    if (windowSum > best) best = windowSum;
  }
  return best;
}

console.log(maxSumWindow([1, 2, 3, 4, 3, 5, 4, 6, 7, 8], 4)); // 25
console.log(maxSumWindow([-1, -2, -3, -4], 2));             // -3

Notice that best starts from the first window's real sum, not from 0. That is why this version handles all-negative arrays correctly without needing -Infinity. In the loop, i is the index of the number entering the window and i - k is the index of the number leaving it.

Trace: Watching the Window Move

The first window [1, 2, 3, 4] sums to 10, so best starts at 10. Each row below is one turn of the second loop:

iLeaves arr[i - k]Enters arr[i]New sumWindow nowbest
41310 − 1 + 3 = 12[2, 3, 4, 3]12
52512 − 2 + 5 = 15[3, 4, 3, 5]15
63415 − 3 + 4 = 16[4, 3, 5, 4]16
74616 − 4 + 6 = 18[3, 5, 4, 6]18
83718 − 3 + 7 = 22[5, 4, 6, 7]22
95822 − 5 + 8 = 25[4, 6, 7, 8]25

The sums match the brute-force table exactly, which is a good habit to check: the fast version must give the same answers as the slow, obvious one. For the 1,00,000-number example above, the sliding window needs about 1,99,000 additions and subtractions instead of 9.9 crore.

Edge Cases: What Should the Function Return?

The original version returned the text "num should be less than arr.length" when the window was too big. That mixes two types in one return value. Code that calls the function expects a number, so a comparison like sol([1, 2, 3], 5) > 2 silently gives false instead of warning anyone. Returning null (or throwing an error) makes the failure obvious.

The old checks also missed a few inputs. With k = 0 or a negative k the brute force returned 0, and the old sliding version returned NaN for a negative or decimal window size. Here is how the corrected maxSumWindow handles each case:

CallResultWhy
maxSumWindow([1, 2], 3)nullWindow is larger than the array
maxSumWindow([1, 2, 3], 0)nullA window of zero numbers makes no sense
maxSumWindow([1, 2, 3], -1)nullNegative size is rejected
maxSumWindow([1, 2, 3], 2.5)nullSize must be a whole number
maxSumWindow([], 1)nullEmpty array has no windows
maxSumWindow([5], 1)5One element, one window
maxSumWindow([4, -1, 2], 3)5k equals the length: the whole array is the only window
maxSumWindow([-1, -2, -3, -4], 2)-3All negatives: the answer is the "least bad" window
maxSumWindow([3, 8, 1], 1)8k = 1 is just the largest element

Time and Space Complexity

ApproachTimeExtra spaceBest for
Brute force (nested loops)O(n·k), up to O(n²) in the worst caseO(1)Small inputs, checking your answers
Sliding windowO(n)O(1)Any real use, and interviews

Both use O(1) extra space, meaning they need only a few variables whatever the size of the array. The sliding window wins on time because its cost does not depend on k at all: a window of 4 and a window of 40,000 take about the same number of steps.

Worked Example: The Best 3-Day Sales Stretch

In real code you usually want to know where the best window is, not just its total. A store owner wants to hear "days 4 to 6", not only "₹70,000". We only need to remember the start position whenever we find a new best:

function bestWindow(sales, k) {
  if (!Number.isInteger(k) || k <= 0 || k > sales.length) return null;

  let windowSum = 0;
  for (let i = 0; i < k; i++) windowSum += sales[i];

  let best = windowSum;
  let bestStart = 0;
  for (let i = k; i < sales.length; i++) {
    windowSum += sales[i] - sales[i - k];
    if (windowSum > best) {
      best = windowSum;
      bestStart = i - k + 1;
    }
  }
  return { total: best, fromDay: bestStart + 1, toDay: bestStart + k };
}

const dailySales = [12, 15, 9, 22, 18, 30, 14, 11, 25, 27]; // ₹ thousand per day
console.log(bestWindow(dailySales, 3)); // { total: 70, fromDay: 4, toDay: 6 }

Because the check is > and not >=, a tie keeps the earliest window. Change it to >= if your business wants the most recent one instead. Small choices like this are worth stating out loud in an interview.

Working with rupees and paise? Decimal amounts are stored inexactly in JavaScript, so 19.99 + 5.49 prints 25.479999999999997. If your sales are in rupees with paise, convert them to whole paise first (1999, 549), run the window on whole numbers, and divide by 100 only when you display the result.

Related Problem: Any Length (Kadane's Algorithm)

A very common follow-up question is: "What if the length is not fixed? Find the largest sum of any run of consecutive numbers." This is called the maximum subarray problem, and a fixed-size sliding window can't solve it, because we don't know how wide the window should be.

The standard answer is Kadane's algorithm. As it walks through the array, it keeps the best sum of a run that ends at the current position. At each number it asks one question: is it better to extend the current run, or to throw it away and start fresh from this number? If the running total has become a drag (negative), starting fresh wins.

function maxSubarraySum(arr) {
  if (arr.length === 0) return null;

  let current = arr[0]; // best sum of a run ending here
  let best = arr[0];    // best sum seen anywhere
  for (let i = 1; i < arr.length; i++) {
    current = Math.max(arr[i], current + arr[i]);
    best = Math.max(best, current);
  }
  return best;
}

console.log(maxSubarraySum([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // 6  (from [4, -1, 2, 1])
console.log(maxSubarraySum([-3, -1, -2]));                    // -1 (a single number)
console.log(maxSubarraySum([]));                              // null

Kadane's algorithm is also O(n) time and O(1) space. Like our sliding window, it starts from arr[0] rather than 0, so it gives the right answer when every number is negative. To gain confidence, compare maxSubarraySum and maxSumWindow with slow brute-force versions on a few hundred random arrays; they should agree every time.

QuestionWindow sizeTechnique
Largest sum of exactly k neighboursFixedSliding window
Largest sum of any run of neighboursAnyKadane's algorithm
Largest sum of any numbers (not neighbours)Not a windowAdd every positive number (or take the largest one if none is positive)

Common Mistakes (and the Fix)

MistakeWhat happensFix
Starting the best sum at 0All-negative arrays return 0, a sum no window hasStart at -Infinity or at the first window's sum
Outer loop i < arr.length instead of i <= arr.length - kReads past the end; arr[10] is undefined, sums become NaN, and with Math.max the final answer is NaNStop the outer loop at arr.length - k
Returning a text message for bad inputThe caller gets a string where it expected a number, and comparisons fail silentlyReturn null or throw a RangeError
Not checking k <= 0 or decimal kResults like 0 or NaN that look like real answersCheck Number.isInteger(k) && k > 0
Confusing "largest sum" with "largest element"Math.max(...arr) gives 8, not 25Re-read the question: it asks for a total of neighbours
Using a fixed window when the length is freeWrong answer for "any length" questionsUse Kadane's algorithm

My Opinion

Write the brute force first, even in an interview. It takes two minutes, it shows you understand the problem, and it becomes your answer key. Then say "this re-adds the overlap, so let's slide instead" and write the O(n) version. That story is exactly what interviewers want to hear.

Never start a "maximum" at 0. Start from the first real value or from -Infinity. This one habit fixes a whole family of bugs, not just in this problem but in any "find the biggest" loop.

Handle bad input in one consistent way. I prefer returning null for "no answer exists" and letting the caller decide what to show. A function that sometimes returns a number and sometimes returns a sentence is harder to use than one that never checks at all.

Test the fast version against the slow one. Run both on a few small and random arrays, including negatives and k equal to the length. If they ever disagree, the clever one is almost always the one that's wrong.

Learn the pattern, not the answer. "Add what enters, remove what leaves" is the core of many sliding window problems: maximum average of size k, counting things in the last 60 seconds, longest substring without repeating characters. Once this clicks, those feel familiar.

Try It Yourself

Work out each answer on paper first, then paste the functions from this post into your browser console (press F12 → Console) to check. Answers are below.

1. maxSumWindow([2, 1, 5, 1, 3, 2], 3)
2. maxSumWindow([-5, -2, -8, -1], 2)
3. maxSumWindow([4, 2], 3)
4. sol([-5, -2, -8, -1], 2)       // the original version, starting at 0
5. How many windows of size 3 fit in an array of 8 numbers?
6. maxSubarraySum([2, -1, 2, 3, -9, 4])
7. maxSumWindow([3, 3, 3], 3)
Show answers
1. 9     → the window [5, 1, 3]
2. -7    → [-5, -2]; the other windows are -10 and -9
3. null  → the window is larger than the array
4. 0     → the bug: no window really sums to 0
5. 6     → 8 - 3 + 1
6. 6     → [2, -1, 2, 3]; Kadane keeps going through the -1
7. 9     → k equals the length, so the whole array is the only window

Frequently Asked Questions

Is the brute force solution wrong?

No, once the starting value is fixed it gives correct answers. It is simply slower, because it re-adds numbers it has already added. It is still useful for small inputs and as a way to test the faster version.

Why is the sliding window faster?

Because each move costs one subtraction and one addition, whatever the window size. The brute force does k additions per window, so its cost grows with both the array length and the window size.

When should I think "sliding window"?

Whenever a question talks about consecutive elements, a continuous subarray or substring, or "the last N" of something. A fixed size gives you this simple version. A size that grows and shrinks (for example "longest substring with no repeats") uses a variable-size window with two pointers.

Does the sliding window work with negative numbers?

Yes. The fixed-size version in this post works with any numbers, as long as you start from the first window's sum. Negative numbers mainly cause trouble for variable-size windows that shrink when the sum gets too big, because that trick assumes every number is positive.

Key Takeaways

  • "Consecutive" means a continuous block; an array of length n has n - k + 1 windows of size k.
  • Brute force is O(n·k): correct, but it re-adds the overlap between windows.
  • The sliding window is O(n): subtract what leaves, add what enters.
  • Never start a maximum at 0; use the first window's sum or -Infinity, or all-negative arrays break.
  • Reject k that is too large, zero, negative or not a whole number, and return null rather than a text message.
  • Track the start index when you need to know where the best window is.
  • For the "any length" version, use Kadane's algorithm, also O(n).

Next, practise another classic array and string problem in the JavaScript anagram problem.

References

Related Articles

Post a Comment

0 Comments