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;
max_sum = max_sum_of_subarray(arr, n, k);
cout << max_sum << endl;
return 0;
}
|
Java
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;
int max_sum = max_sum_of_subarray(arr, n, k);
System.out.println(max_sum);
}
}
|
Python3
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 ;
max_sum = max_sum_of_subarray(arr, n, k);
print (max_sum);
|
C#
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;
max_sum = max_sum_of_subarray(arr, n, k);
Console.Write(max_sum);
}
}
|
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;
max_sum = max_sum_of_subarray(arr, n, k);
console.log(max_sum);
|
Output
Max 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++
#include <bits/stdc++.h>
using namespace std;
int maxSum( int arr[], int n, int k)
{
if (n < k) {
cout << "Invalid" ;
return -1;
}
queue< int > q;
int m = INT_MIN;
int su = 0;
for ( int i = 0; i < k; i++) {
q.push(arr[i]);
su += arr[i];
}
for ( int i = k; i < n; i++) {
su -= q.front();
q.pop();
q.push(arr[i]);
su += arr[i];
m = max(m, su);
}
return m;
}
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
import java.util.LinkedList;
import java.util.Queue;
class GFG {
static int maxSum( int arr[], int n, int k)
{
if (n < k) {
System.out.println( "Invalid" );
return - 1 ;
}
Queue<Integer> q = new LinkedList<Integer>();
int m = Integer.MIN_VALUE;
int su = 0 ;
for ( int i = 0 ; i < k; i++) {
q.add(arr[i]);
su += arr[i];
}
for ( int i = k; i < n; i++) {
su -= q.peek();
q.remove();
q.add(arr[i]);
su += arr[i];
m = Math.max(m, su);
}
return m;
}
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));
}
}
|
Python3
from collections import deque
def maxSum(arr, n, k):
if (n < k):
print ( "Invalid" )
return - 1
q = deque()
m = float ( '-inf' )
su = 0
for i in range (k):
q.append(arr[i])
su + = arr[i]
for i in range (k, n):
su - = q[ 0 ]
q.popleft()
q.append(arr[i])
su + = arr[i]
m = max (m, su)
return m
arr = [ 1 , 4 , 2 , 10 , 2 , 3 , 1 , 0 , 20 ]
k = 4
n = len (arr)
print (maxSum(arr, n, k))
|
C#
using System;
using System.Collections.Generic;
class MainClass {
static int maxSum( int [] arr, int n, int k)
{
if (n < k) {
Console.WriteLine( "Invalid" );
return -1;
}
Queue< int > q = new Queue< int >();
int m = int .MinValue;
int su = 0;
for ( int i = 0; i < k; i++) {
q.Enqueue(arr[i]);
su += arr[i];
}
for ( int i = k; i < n; i++) {
su -= q.Peek();
q.Dequeue();
q.Enqueue(arr[i]);
su += arr[i];
m = Math.Max(m, su);
}
return m;
}
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));
}
}
|
Javascript
function maxSum(arr, n, k) {
if (n < k) {
console.log( "Invalid" );
return -1;
}
const q = [];
let m = Number.MIN_SAFE_INTEGER;
let su = 0;
for (let i = 0; i < k; i++) {
q.push(arr[i]);
su += arr[i];
}
for (let i = k; i < n; i++) {
su -= q.shift();
q.push(arr[i]);
su += arr[i];
m = Math.max(m, su);
}
return m;
}
const arr = [1, 4, 2, 10, 2, 3, 1, 0, 20];
const k = 4;
const n = arr.length;
console.log(maxSum(arr, n, k));
|
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++
#include <iostream>
using namespace std;
int maxSum( int arr[], int n, int k)
{
if (n < k)
{
cout << "Invalid" ;
return -1;
}
int res = 0;
for ( int i=0; i<k; i++)
res += arr[i];
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;
}
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
import java.util.*;
class GFG {
public static int maxSum( int arr[], int n, int k)
{
if (n < k)
{
System.out.println( "Invalid" );
return - 1 ;
}
int res = 0 ;
for ( int i= 0 ; i<k; i++)
res += arr[i];
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;
}
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));
}
}
|
Python3
def maxSum(arr, n, k):
if (n < k):
print ( "Invalid" )
return - 1
res = 0
for i in range (k):
res + = arr[i]
curr_sum = res
for i in range (k, n):
curr_sum + = arr[i] - arr[i - k]
res = max (res, curr_sum)
return res
arr = [ 1 , 4 , 2 , 10 , 2 , 3 , 1 , 0 , 20 ]
k = 4
n = len (arr)
print (maxSum(arr, n, k))
|
C#
using System;
class GFG {
public static int maxSum( int []arr,
int n,
int k)
{
if (n < k)
{
Console.Write( "Invalid" );
return -1;
}
int res = 0;
for ( int i = 0; i < k; i++)
res += arr[i];
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;
}
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));
}
}
|
PHP
<?php
function maxSum( $arr , $n , $k )
{
if ( $n < $k )
{
echo "Invalid" ;
return -1;
}
$res = 0;
for ( $i = 0; $i < $k ; $i ++)
$res += $arr [ $i ];
$curr_sum = $res ;
for ( $i = $k ; $i < $n ; $i ++)
{
$curr_sum += $arr [ $i ] -
$arr [ $i - $k ];
$res = max( $res , $curr_sum );
}
return $res ;
}
$arr = array (1, 4, 2, 10, 2, 3, 1, 0, 20);
$k = 4;
$n = sizeof( $arr );
echo maxSum( $arr , $n , $k );
?>
|
Javascript
<script>
function maxSum(arr,n,k)
{
if (n < k)
{
document.write( "Invalid" );
return -1;
}
let res = 0;
for (let i=0; i<k; i++)
res += arr[i];
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;
}
let arr = [1, 4, 2, 10, 2, 3, 1, 0, 20];
let k = 4;
let n = arr.length;
document.write(maxSum(arr, n, k));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
This article is contributed by Abhishek Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.