~/coding-interview/sliding-window.md

Find the maximum sum of any continuous subarray of size K

2 min readDecember 23, 2020by Gorav Singal#coding-interview#sliding-window-pattern
// TL;DR

Sliding window avoids recomputing the entire subarray sum — subtract the element leaving the window and add the one entering. Reduces O(n*k) brute force to O(n).

Find the maximum sum of any continuous subarray of size K

Introduction

You are given an array of integers with size N, and a number K. Find the maximum sum of continuous subarray of size K.

Example

Input: [1, 2, 6, 2, 4, 1], k=3 
Output: 12
Explanation: Subarray with maximum sum is [6, 2, 4].

Solution (Brute Force)

Brute Force Solution

You need to keep sum of the subarray of size=k all the time, and keep on iterating.

Code

public int findMaxSum(int[] arr, int k) {
  int max=0;
  for (int i=0; i<=arr.length-k; i++) {
    int sum_k = 0;
    for (int j=i; j<i+k; j++) {
      sum_k += arr[j];
    }
    max = Math.max(max, sum_k);
  }
  return max;
}

Complexity

There are two loops

  1. n-k times != n
  2. k times

Total of O(nk)*

Solution (Sliding Window Pattern)

If you observe problem and above solution closely,

  • you need to keep continuous array
  • size should be K

When you first calculate sum of the first window size of K. You already have the sum of previous window. To get the sum of next window. You need to remove first number of previous window, and add next number. So effectively you are using the sum of previous window sum. You need not to go to calculate whole sum again.

Example

1 2 3 4 5

First window = 1 2 3, sum=6

For next window, subtract 1 from sum, and add 4 to remaining sum.
Second window = 2 3 4
  i.e. 6 - 1 + 4 = 9

In this way, we are effectively moving our window from begining to end and we need to keep the max sum available till each window.

Lets look at the code.

Code

public int findMaxSum(int[] arr, int k) {
  int max = 0;
  int left = 0;
  int right = 0;

  int window_sum = 0;
  while (right < arr.length) {
    window_sum += arr[right];
    if (right >= k) {
      max = Math.max(max, window_sum);

      //subtract first number of previous widow
      window_sum -= arr[left];
      
      //move left pointer to next number
      left ++;
    }
  }

  return max;
}

We are keeping two pointers for window left and right. On completing the window size, we subtract first number of last window and keep a tab of the max sum available.

Complexity

We are iterating over array just once. Its O(n)

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

System Design Interview Vocabulary Notes

System Design Interview Vocabulary Notes

In this post, we will see some of the frequently used concepts/vocabulary in…

Coding Interview - Facebook System Design Interview Types

Coding Interview - Facebook System Design Interview Types

System design interview is pretty common these days, specially if you are having…

What FAANG companies expect in their interview from candidates

What FAANG companies expect in their interview from candidates

Its every software engineer’s dream to work with the big FAANG companies…

Magical usage of Bitwise operators - Get optimized solutions for many arithmatic problems

Magical usage of Bitwise operators - Get optimized solutions for many arithmatic problems

Introduction I will list some of the interesting usage of bitwise operators…

How to prepare for your next Coding Interview

How to prepare for your next Coding Interview

Here are some tips while preparing for your coding interviews. 1. Do study or…

Radix Sort Algorithm

Radix Sort Algorithm

A number consists of digits. Example: 843. Its a 3-digit number. Radix sort…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…