Find maximum (or minimum) sum of a subarray of size k

Given an array of integers and a number k, find 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
We get maximum sum by adding subarray {4, 2, 10, 23}
of size 4.

Input  : arr[] = {2, 3}
         k = 3
Output : Invalid
There is no subarray of size 3 as size of whole
array is 2.

A Simple Solution is to generate all subarrays of size k, compute their sums and finally return maximum of all sums. Time complexity of this solution is O(n*k)

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 sum of previous subarray (or window) of size k. Except first subarray of size k, for other subarrays, we compute sum by removing first element of last window and adding last element of current window.

Below is implementation of above idea.

C

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 greater
    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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 greater
        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.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 greater
    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.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 greater
        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.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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 greater
    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.
?>

chevron_right



Output :

24

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 contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up

Improved By : nitin mittal