Find maximum (or minimum) sum of a subarray of size k
Last Updated :
23 Jul, 2025
Given an array of integers and a number k, find the maximum sum of a subarray of size k.
Examples:
Input : arr[] = {100, 200, 300, 400}, k = 2
Output : 700
Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}, k = 4
Output : 39
Explanation: We get maximum sum by adding subarray {4, 2, 10, 23} of size 4.
Input : arr[] = {2, 3}, k = 3
Output : Invalid
Explanation: There is no subarray of size 3 as size of whole array is 2.
Naive Solution :
A Simple Solution is to generate all subarrays of size k, compute their sums and finally return the maximum of all sums. The time complexity of this solution is O(n*k).
Below is the implementation of the above idea.
C++
#include <bits/stdc++.h>
using namespace std;
int max_sum_of_subarray(int arr[], int n, int k)
{
int max_sum = 0;
for (int i = 0; i + k <= n; i++) {
int temp = 0;
for (int j = i; j < i + k; j++) {
temp += arr[j];
}
if (temp > max_sum)
max_sum = temp;
}
return max_sum;
}
int main()
{
int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
int k = 4;
int n = sizeof(arr) / sizeof(int);
int max_sum;
// by brute force
max_sum = max_sum_of_subarray(arr, n, k);
cout << max_sum << endl;
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
public class GFG {
static int max_sum_of_subarray(int arr[], int n, int k)
{
int max_sum = 0;
for (int i = 0; i + k <= n; i++) {
int temp = 0;
for (int j = i; j < i + k; j++) {
temp += arr[j];
}
if (temp > max_sum)
max_sum = temp;
}
return max_sum;
}
public static void main(String[] args)
{
int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
int k = 4;
int n = arr.length;
// by brute force
int max_sum = max_sum_of_subarray(arr, n, k);
System.out.println(max_sum);
}
}
// This code is contributed by Karandeep1234
Python
def max_sum_of_subarray(arr, n, k):
max_sum = 0;
for i in range(0, n-k+1):
temp = 0;
for j in range(i, i+k):
temp += arr[j];
if (temp > max_sum):
max_sum = temp;
return max_sum;
arr = [ 1, 4, 2, 10, 2, 3, 1, 0, 20 ];
k = 4;
n = len(arr);
max_sum=0;
# brute force
max_sum = max_sum_of_subarray(arr, n, k);
print(max_sum);
# This code is contributed by poojaagarwal2.
C#
// C# program to demonstrate deletion in
// Ternary Search Tree (TST)
// For insert and other functions, refer
// https://www.geeksforgeeks.org/dsa/ternary-search-tree/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
public class Gfg
{
static int max_sum_of_subarray(int[] arr, int n, int k)
{
int max_sum = 0;
for (int i = 0; i + k <= n; i++) {
int temp = 0;
for (int j = i; j < i + k; j++) {
temp += arr[j];
}
if (temp > max_sum)
max_sum = temp;
}
return max_sum;
}
public static void Main(string[] args)
{
int[] arr = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
int k = 4;
int n = arr.Length;
int max_sum;
// by brute force
max_sum = max_sum_of_subarray(arr, n, k);
Console.Write(max_sum);
}
}
// This code is contributed by agrawalpoojaa976.
JavaScript
function max_sum_of_subarray(arr, n, k)
{
let max_sum = 0;
for (let i = 0; i + k <= n; i++) {
let temp = 0;
for (let j = i; j < i + k; j++) {
temp += arr[j];
}
if (temp > max_sum)
max_sum = temp;
}
return max_sum;
}
let arr = [ 1, 4, 2, 10, 2, 3, 1, 0, 20 ];
let k = 4;
let n = arr.length;
let max_sum;
// by brute force
max_sum = max_sum_of_subarray(arr, n, k);
console.log(max_sum);
// This code is contributed by ritaagarwal.
OutputMax Sum By Brute Force :24
Time Complexity: O(n2)
Auxiliary Space: O(1)
Using Queue:
We can use queue structure to calculate max or min sum of a subarray of size k.
Algorithm:
- First create an queue structure and push k elements inside it and calculate the sum of the elements (let's say su) during pushing.
- Now create a max/min variable (let's say m) with value INT_MIN for max value or INT_MAX for min value.
- Then iterate using loop from kth position to the end of the array.
- During each iteration do below steps:
- First subtract su with the front element of the queue.
- Then pop it from the queue.
- Now, push the current element of the array inside queue and add it to the su.
- Then compare it with the value m for max/min.
- Now, print the current m value.
Below is the implementation of the above approach:
C++
// O(n) solution for finding maximum sum of
// a subarray of size k with O(k) space
#include <bits/stdc++.h>
using namespace std;
// Returns maximum sum in a subarray of size k.
int maxSum(int arr[], int n, int k)
{
// k must be smaller than n
if (n < k) {
cout << "Invalid";
return -1;
}
// Create Queue
queue<int> q;
int m = INT_MIN;
int su = 0;
// Compute sum of first k elements and also
// store then inside queue
for (int i = 0; i < k; i++) {
q.push(arr[i]);
su += arr[i];
}
for (int i = k; i < n; i++) {
m = max(m, su);
su -= q.front();
q.pop();
q.push(arr[i]);
su += arr[i];
}
m = max(m, su);
return m;
}
// Driver code
int main()
{
int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
int k = 4;
int n = sizeof(arr) / sizeof(arr[0]);
cout << maxSum(arr, n, k);
return 0;
}
// This code is contributed by Susobhan Akhuli
Java
// Java equivalent code
import java.util.LinkedList;
import java.util.Queue;
class GFG {
// Function to find maximum sum of
// a subarray of size k
static int maxSum(int arr[], int n, int k)
{
// k must be smaller than n
if (n < k) {
System.out.println("Invalid");
return -1;
}
// Create Queue
Queue<Integer> q = new LinkedList<Integer>();
// Initialize maximum and current sum
int m = Integer.MIN_VALUE;
int su = 0;
// Compute sum of first k elements
// and also store them inside queue
for (int i = 0; i < k; i++) {
q.add(arr[i]);
su += arr[i];
}
// Compute sum of remaining elements
for (int i = k; i < n; i++) {
m = Math.max(m, su);
// remove first element from the queue
su -= q.peek();
q.remove();
// add current element to the queue
q.add(arr[i]);
su += arr[i];
// update maximum sum
}
m = Math.max(m, su);
return m;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
int k = 4;
int n = arr.length;
System.out.println(maxSum(arr, n, k));
}
}
// This code is contributed by Susobhan Akhuli
Python
from collections import deque
def maxSum(arr, n, k):
# k must be smaller than n
if n < k:
print("Invalid")
return -1
# Create deque
q = deque()
# Initialize maximum and current sum
m = float('-inf')
su = 0
# Compute sum of first k elements
# and also store them inside deque
for i in range(k):
q.append(arr[i])
su += arr[i]
# Compute sum of remaining elements
for i in range(k, n):
m = max(m, su)
# Remove first element from the deque
su -= q[0]
q.popleft()
# Add current element to the deque
q.append(arr[i])
su += arr[i]
# Update maximum sum for the last window
m = max(m, su)
return m
# Driver code
arr = [ 1, 4, 2, 10, 2, 3, 1, 0, 20]
k = 4
n = len(arr)
print(maxSum(arr, n, k))
C#
// O(n) solution for finding maximum sum of
// a subarray of size k with O(k) space
using System;
using System.Collections.Generic;
class MainClass {
// Returns maximum sum in a subarray of size k.
static int maxSum(int[] arr, int n, int k)
{
// k must be smaller than n
if (n < k) {
Console.WriteLine("Invalid");
return -1;
}
// Create Queue
Queue<int> q = new Queue<int>();
int m = int.MinValue;
int su = 0;
// Compute sum of first k elements and also
// store then inside queue
for (int i = 0; i < k; i++) {
q.Enqueue(arr[i]);
su += arr[i];
}
for (int i = k; i < n; i++) {
m = Math.Max(m, su);
su -= q.Peek();
q.Dequeue();
q.Enqueue(arr[i]);
su += arr[i];
}
m = Math.Max(m, su);
return m;
}
// Driver code
public static void Main(string[] args)
{
int[] arr = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
int k = 4;
int n = arr.Length;
Console.WriteLine(maxSum(arr, n, k));
}
}
// This code is contributed by Susobhan Akhuli
JavaScript
// JavaScript solution for finding maximum sum of
// a subarray of size k with O(k) space
// Returns maximum sum in a subarray of size k.
function maxSum(arr, n, k)
{
// k must be smaller than n
if (n < k) {
console.log("Invalid");
return -1;
}
// Create Queue
const q = [];
let m = Number.MIN_SAFE_INTEGER;
let su = 0;
// Compute sum of first k elements and also
// store then inside queue
for (let i = 0; i < k; i++) {
q.push(arr[i]);
su += arr[i];
}
for (let i = k; i < n; i++) {
m = Math.max(m, su);
su -= q.shift();
q.push(arr[i]);
su += arr[i];
}
m = Math.max(m, su);
return m;
}
// Driver code
const arr = [ 1, 4, 2, 10, 2, 3, 1, 0, 20 ];
const k = 4;
const n = arr.length;
console.log(maxSum(arr, n, k));
// This code is contributed by Susobhan Akhuli.
Time Complexity: O(n), to iterate n times.
Auxiliary Space: O(k) , to store k elements inside queue.
Optimized Solution (Space Optimization) :
An Efficient Solution is based on the fact that sum of a subarray (or window) of size k can be obtained in O(1) time using the sum of the previous subarray (or window) of size k. Except for the first subarray of size k, for other subarrays, we compute the sum by removing the first element of the last window and adding the last element of the current window.
Below is the implementation of the above idea.
C++
// O(n) solution for finding maximum sum of
// a subarray of size k
#include <iostream>
using namespace std;
// Returns maximum sum in a subarray of size k.
int maxSum(int arr[], int n, int k)
{
// k must be smaller than n
if (n < k)
{
cout << "Invalid";
return -1;
}
// Compute sum of first window of size k
int res = 0;
for (int i=0; i<k; i++)
res += arr[i];
// Compute sums of remaining windows by
// removing first element of previous
// window and adding last element of
// current window.
int curr_sum = res;
for (int i=k; i<n; i++)
{
curr_sum += arr[i] - arr[i-k];
res = max(res, curr_sum);
}
return res;
}
// Driver code
int main()
{
int arr[] = {1, 4, 2, 10, 2, 3, 1, 0, 20};
int k = 4;
int n = sizeof(arr)/sizeof(arr[0]);
cout << maxSum(arr, n, k);
return 0;
}
Java
// JAVA Code for Find maximum (or minimum)
// sum of a subarray of size k
import java.util.*;
class GFG {
// Returns maximum sum in a subarray of size k.
public static int maxSum(int arr[], int n, int k)
{
// k must be smaller than n
if (n < k)
{
System.out.println("Invalid");
return -1;
}
// Compute sum of first window of size k
int res = 0;
for (int i=0; i<k; i++)
res += arr[i];
// Compute sums of remaining windows by
// removing first element of previous
// window and adding last element of
// current window.
int curr_sum = res;
for (int i=k; i<n; i++)
{
curr_sum += arr[i] - arr[i-k];
res = Math.max(res, curr_sum);
}
return res;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr[] = {1, 4, 2, 10, 2, 3, 1, 0, 20};
int k = 4;
int n = arr.length;
System.out.println(maxSum(arr, n, k));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python
# O(n) solution in Python3 for finding
# maximum sum of a subarray of size k
# Returns maximum sum in
# a subarray of size k.
def maxSum(arr, n, k):
# k must be smaller than n
if (n < k):
print("Invalid")
return -1
# Compute sum of first
# window of size k
res = 0
for i in range(k):
res += arr[i]
# Compute sums of remaining windows by
# removing first element of previous
# window and adding last element of
# current window.
curr_sum = res
for i in range(k, n):
curr_sum += arr[i] - arr[i-k]
res = max(res, curr_sum)
return res
# Driver code
arr = [1, 4, 2, 10, 2, 3, 1, 0, 20]
k = 4
n = len(arr)
print(maxSum(arr, n, k))
# This code is contributed by Anant Agarwal.
C#
// C# Code for Find maximum (or minimum)
// sum of a subarray of size k
using System;
class GFG {
// Returns maximum sum in
// a subarray of size k.
public static int maxSum(int []arr,
int n,
int k)
{
// k must be smaller than n
if (n < k)
{
Console.Write("Invalid");
return -1;
}
// Compute sum of first window of size k
int res = 0;
for (int i = 0; i < k; i++)
res += arr[i];
// Compute sums of remaining windows by
// removing first element of previous
// window and adding last element of
// current window.
int curr_sum = res;
for (int i = k; i < n; i++)
{
curr_sum += arr[i] - arr[i - k];
res = Math.Max(res, curr_sum);
}
return res;
}
// Driver Code
public static void Main()
{
int []arr = {1, 4, 2, 10, 2, 3, 1, 0, 20};
int k = 4;
int n = arr.Length;
Console.Write(maxSum(arr, n, k));
}
}
// This code is contributed by nitin mittal.
JavaScript
<script>
// JAVA SCRIPT Code for Find maximum (or minimum)
// sum of a subarray of size k
// Returns maximum sum in a subarray of size k.
function maxSum(arr,n,k)
{
// k must be smaller than n
if (n < k)
{
document.write("Invalid");
return -1;
}
// Compute sum of first window of size k
let res = 0;
for (let i=0; i<k; i++)
res += arr[i];
// Compute sums of remaining windows by
// removing first element of previous
// window and adding last element of
// current window.
let curr_sum = res;
for (let i=k; i<n; i++)
{
curr_sum += arr[i] - arr[i-k];
res = Math.max(res, curr_sum);
}
return res;
}
/* Driver program to test above function */
let arr = [1, 4, 2, 10, 2, 3, 1, 0, 20];
let k = 4;
let n = arr.length;
document.write(maxSum(arr, n, k));
// This code is contributed by sravan kumar Gottumukkala
</script>
PHP
<?php
// O(n) solution for finding maximum
// sum of a subarray of size k
// Returns maximum sum in a
// subarray of size k.
function maxSum($arr, $n, $k)
{
// k must be smaller than n
if ($n < $k)
{
echo "Invalid";
return -1;
}
// Compute sum of first
// window of size k
$res = 0;
for($i = 0; $i < $k; $i++)
$res += $arr[$i];
// Compute sums of remaining windows by
// removing first element of previous
// window and adding last element of
// current window.
$curr_sum = $res;
for($i = $k; $i < $n; $i++)
{
$curr_sum += $arr[$i] -
$arr[$i - $k];
$res = max($res, $curr_sum);
}
return $res;
}
// Driver Code
$arr = array(1, 4, 2, 10, 2, 3, 1, 0, 20);
$k = 4;
$n = sizeof($arr);
echo maxSum($arr, $n, $k);
// This code is contributed by nitin mittal.
?>
Time Complexity: O(n)
Auxiliary Space: O(1)
PROBLEM OF THE DAY : 11/12/2023 | Max Sum Subarray of size K
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem