Maximum Sum Subarray of Size K — Coding Interview | Sliding Window | 30 Days Preparation Plan | Day 4 — Problem 1

Ganesh Prasad
Javarevisited
Published in
4 min readSep 27, 2021

--

This problem is easy and fun 🥳; hence an appropriate example to introduce the sliding window pattern. The strategy is similar to Smallest Subarray with a Given Sum.

For a better grasp of the problem, after reading each section, try to code that approach. If you get stuck 😉, you can always look at the commented code I have provided for your reference.

This problem is part of the 30 Days Preparation Plan.

Table of Contents

  1. Description
  2. Brute Force Approach
  3. Code
  4. Time & Space Complexity
  5. Efficient Approach — Sliding Window
  6. Code
  7. Time & Space Complexity

Description

You have an array of N positive integers and a positive integer K. You have to find the Maximum Sum Subarray of size K.

We will find the maximum sum, but it is easy to print the subarray too. We will see how.

Example 1:
Input: [4 3 9 5 1 2], K = 3
Output: 17
Explanation: The subarray of size 3 with maximum sum 17 is [3 9 5].

--

--

Ganesh Prasad
Javarevisited

Backend Developer at Appscrip | C++ veteran, 💜 Dart