Find maximum average subarray of k length
Last Updated :
23 Jul, 2025
Given an array with positive and negative numbers, find the maximum average subarray of the given length.
Example:
Input: arr[] = {1, 12, -5, -6, 50, 3}, k = 4
Output: Maximum average subarray of length 4 begins
at index 1.
Maximum average is (12 - 5 - 6 + 50)/4 = 51/4
A Simple Solution is to run two loops. The outer loop picks starting point, and the inner loop goes to length 'k' from the starting point and computes the average of elements.
Time Complexity: O(n*k), as we are using nested loops to traverse n*k times.
Auxiliary Space: O(1), as we are not using any extra space.
A Better Solution is to create an auxiliary array of size n. Store cumulative sum of elements in this array. Let the array be csum[]. csum[i] stores sum of elements from arr[0] to arr[i]. Once we have the csum[] array with us, we can compute the sum between two indexes in O(1) time.
Below is the implementation of this idea. One observation is, that a subarray of a given length has a maximum average if it has a maximum sum. So we can avoid floating-point arithmetic by just comparing sums.
C++
// C++ program to find maximum average subarray
// of given length.
#include<bits/stdc++.h>
using namespace std;
// Returns beginning index of maximum average
// subarray of length 'k'
int findMaxAverage(int arr[], int n, int k)
{
// Check if 'k' is valid
if (k > n)
return -1;
// Create and fill array to store cumulative
// sum. csum[i] stores sum of arr[0] to arr[i]
int *csum = new int[n];
csum[0] = arr[0];
for (int i=1; i<n; i++)
csum[i] = csum[i-1] + arr[i];
// Initialize max_sm as sum of first subarray
int max_sum = csum[k-1], max_end = k-1;
// Find sum of other subarrays and update
// max_sum if required.
for (int i=k; i<n; i++)
{
int curr_sum = csum[i] - csum[i-k];
if (curr_sum > max_sum)
{
max_sum = curr_sum;
max_end = i;
}
}
delete [] csum; // To avoid memory leak
// Return starting index
return max_end - k + 1;
}
// Driver program
int main()
{
int arr[] = {1, 12, -5, -6, 50, 3};
int k = 4;
int n = sizeof(arr)/sizeof(arr[0]);
cout << "The maximum average subarray of "
"length "<< k << " begins at index "
<< findMaxAverage(arr, n, k);
return 0;
}
Java
// Java program to find maximum average
// subarray of given length.
import java .io.*;
class GFG {
// Returns beginning index
// of maximum average
// subarray of length 'k'
static int findMaxAverage(int []arr,
int n, int k)
{
// Check if 'k' is valid
if (k > n)
return -1;
// Create and fill array
// to store cumulative
// sum. csum[i] stores
// sum of arr[0] to arr[i]
int []csum = new int[n];
csum[0] = arr[0];
for (int i = 1; i < n; i++)
csum[i] = csum[i - 1] + arr[i];
// Initialize max_sm as
// sum of first subarray
int max_sum = csum[k - 1],
max_end = k - 1;
// Find sum of other
// subarrays and update
// max_sum if required.
for (int i = k; i < n; i++)
{
int curr_sum = csum[i] -
csum[i - k];
if (curr_sum > max_sum)
{
max_sum = curr_sum;
max_end = i;
}
}
// To avoid memory leak
//delete [] csum;
// Return starting index
return max_end - k + 1;
}
// Driver Code
static public void main (String[] args)
{
int []arr = {1, 12, -5, -6, 50, 3};
int k = 4;
int n = arr.length;
System.out.println("The maximum "
+ "average subarray of length "
+ k + " begins at index "
+ findMaxAverage(arr, n, k));
}
}
// This code is contributed by anuj_67.
Python3
# Python program to find maximum average subarray
# of given length.
# Returns beginning index of maximum average
# subarray of length 'k'
def findMaxAverage(arr, n, k):
# Check if 'k' is valid
if k > n:
return -1
# Create and fill array to store cumulative
# sum. csum[i] stores sum of arr[0] to arr[i]
csum = [0]*n
csum[0] = arr[0]
for i in range(1, n):
csum[i] = csum[i-1] + arr[i];
# Initialize max_sm as sum of first subarray
max_sum = csum[k-1]
max_end = k-1
# Find sum of other subarrays and update
# max_sum if required.
for i in range(k, n):
curr_sum = csum[i] - csum[i-k]
if curr_sum > max_sum:
max_sum = curr_sum
max_end = i
# Return starting index
return max_end - k + 1
# Driver program
arr = [1, 12, -5, -6, 50, 3]
k = 4
n = len(arr)
print("The maximum average subarray of length",k,
"begins at index",findMaxAverage(arr, n, k))
#This code is contributed by
#Smitha Dinesh Semwal
C#
// C# program to find maximum average
// subarray of given length.
using System;
class GFG{
// Returns beginning index
// of maximum average
// subarray of length 'k'
static int findMaxAverage(int []arr,
int n, int k)
{
// Check if 'k' is valid
if (k > n)
return -1;
// Create and fill array
// to store cumulative
// sum. csum[i] stores
// sum of arr[0] to arr[i]
int []csum = new int[n];
csum[0] = arr[0];
for (int i = 1; i < n; i++)
csum[i] = csum[i - 1] + arr[i];
// Initialize max_sm as
// sum of first subarray
int max_sum = csum[k - 1],
max_end = k - 1;
// Find sum of other
// subarrays and update
// max_sum if required.
for (int i = k; i < n; i++)
{
int curr_sum = csum[i] -
csum[i - k];
if (curr_sum > max_sum)
{
max_sum = curr_sum;
max_end = i;
}
}
// To avoid memory leak
//delete [] csum;
// Return starting index
return max_end - k + 1;
}
// Driver Code
static public void Main ()
{
int []arr = {1, 12, -5, -6, 50, 3};
int k = 4;
int n = arr.Length;
Console.WriteLine("The maximum average subarray of "+
"length "+ k + " begins at index "
+ findMaxAverage(arr, n, k));
}
}
// This code is contributed by anuj_67.
JavaScript
<script>
// Javascript program to find maximum average
// subarray of given length.
// Returns beginning index
// of maximum average
// subarray of length 'k'
function findMaxAverage(arr, n, k)
{
// Check if 'k' is valid
if (k > n)
return -1;
// Create and fill array
// to store cumulative
// sum. csum[i] stores
// sum of arr[0] to arr[i]
let csum = new Array(n);
csum[0] = arr[0];
for(let i = 1; i < n; i++)
csum[i] = csum[i - 1] + arr[i];
// Initialize max_sm as
// sum of first subarray
let max_sum = csum[k - 1],
max_end = k - 1;
// Find sum of other
// subarrays and update
// max_sum if required.
for(let i = k; i < n; i++)
{
let curr_sum = csum[i] - csum[i - k];
if (curr_sum > max_sum)
{
max_sum = curr_sum;
max_end = i;
}
}
// To avoid memory leak
//delete [] csum;
// Return starting index
return max_end - k + 1;
}
// Driver code
let arr = [ 1, 12, -5, -6, 50, 3 ];
let k = 4;
let n = arr.length;
document.write("The maximum average subarray of "+
"length "+ k + " begins at index " +
findMaxAverage(arr, n, k));
// This code is contributed by divyeshrabadiya07
</script>
PHP
<?php
// PHP program to find maximum
// average subarray of given length.
// Returns beginning index of
// maximum average subarray of
// length 'k'
function findMaxAverage($arr, $n, $k)
{
// Check if 'k' is valid
if ($k > $n)
return -1;
// Create and fill array to
// store cumulative sum.
// csum[i] stores sum of
// arr[0] to arr[i]
$csum = array();
$csum[0] = $arr[0];
for($i = 1; $i < $n; $i++)
$csum[$i] = $csum[$i - 1] +
$arr[$i];
// Initialize max_sm as sum
// of first subarray
$max_sum = $csum[$k - 1];
$max_end = $k - 1;
// Find sum of other subarrays
// and update max_sum if required.
for($i = $k; $i < $n; $i++)
{
$curr_sum = $csum[$i] -
$csum[$i - $k];
if ($curr_sum > $max_sum)
{
$max_sum = $curr_sum;
$max_end = $i;
}
}
// Return starting index
return $max_end - $k + 1;
}
// Driver Code
$arr = array(1, 12, -5, -6, 50, 3);
$k = 4;
$n = count($arr);
echo "The maximum average subarray of "
,"length ", $k , " begins at index "
, findMaxAverage($arr, $n, $k);
// This code is contributed by anuj_67.
?>
OutputThe maximum average subarray of length 4 begins at index 1
Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of elements in the array.
Auxiliary Space: O(n), as we are using extra space for the array csum.
We can avoid the need for extra space by using the below
Efficient Method.
- Compute sum of first 'k' elements, i.e., elements arr[0..k-1]. Let this sum be 'sum'. Initialize 'max_sum' as 'sum'
- Do following for every element arr[i] where i varies from 'k' to 'n-1'
- Remove arr[i-k] from sum and add arr[i], i.e., do sum += arr[i] - arr[i-k]
- If new sum becomes more than max_sum so far, update max_sum.
- Return 'max_sum'
C++
// C++ program to find maximum average subarray
// of given length.
#include<bits/stdc++.h>
using namespace std;
// Returns beginning index of maximum average
// subarray of length 'k'
int findMaxAverage(int arr[], int n, int k)
{
// Check if 'k' is valid
if (k > n)
return -1;
// Compute sum of first 'k' elements
int sum = arr[0];
for (int i=1; i<k; i++)
sum += arr[i];
int max_sum = sum, max_end = k-1;
// Compute sum of remaining subarrays
for (int i=k; i<n; i++)
{
sum = sum + arr[i] - arr[i-k];
if (sum > max_sum)
{
max_sum = sum;
max_end = i;
}
}
// Return starting index
return max_end - k + 1;
}
// Driver program
int main()
{
int arr[] = {1, 12, -5, -6, 50, 3};
int k = 4;
int n = sizeof(arr)/sizeof(arr[0]);
cout << "The maximum average subarray of "
"length "<< k << " begins at index "
<< findMaxAverage(arr, n, k);
return 0;
}
Java
// Java program to find maximum average subarray
// of given length.
import java.io.*;
class GFG {
// Returns beginning index of maximum average
// subarray of length 'k'
static int findMaxAverage(int arr[], int n, int k)
{
// Check if 'k' is valid
if (k > n)
return -1;
// Compute sum of first 'k' elements
int sum = arr[0];
for (int i = 1; i < k; i++)
sum += arr[i];
int max_sum = sum, max_end = k-1;
// Compute sum of remaining subarrays
for (int i = k; i < n; i++)
{
sum = sum + arr[i] - arr[i-k];
if (sum > max_sum)
{
max_sum = sum;
max_end = i;
}
}
// Return starting index
return max_end - k + 1;
}
// Driver program
public static void main (String[] args)
{
int arr[] = {1, 12, -5, -6, 50, 3};
int k = 4;
int n = arr.length;
System.out.println( "The maximum average"
+ " subarray of length " + k
+ " begins at index "
+ findMaxAverage(arr, n, k));
}
}
// This code is contributed by anuj_67.
Python3
# Python 3 program to find maximum
# average subarray of given length.
# Returns beginning index of maximum
# average subarray of length 'k'
def findMaxAverage(arr, n, k):
# Check if 'k' is valid
if (k > n):
return -1
# Compute sum of first 'k' elements
sum = arr[0]
for i in range(1, k):
sum += arr[i]
max_sum = sum
max_end = k - 1
# Compute sum of remaining subarrays
for i in range(k, n):
sum = sum + arr[i] - arr[i - k]
if (sum > max_sum):
max_sum = sum
max_end = i
# Return starting index
return max_end - k + 1
# Driver program
arr = [1, 12, -5, -6, 50, 3]
k = 4
n = len(arr)
print("The maximum average subarray of length", k,
"begins at index",
findMaxAverage(arr, n, k))
# This code is contributed by
# Smitha Dinesh Semwal
C#
// C# program to find maximum average
// subarray of given length.
using System;
class GFG {
// Returns beginning index of
// maximum average subarray of
// length 'k'
static int findMaxAverage(int []arr,
int n, int k)
{
// Check if 'k' is valid
if (k > n)
return -1;
// Compute sum of first 'k'
// elements
int sum = arr[0];
for (int i = 1; i < k; i++)
sum += arr[i];
int max_sum = sum;
int max_end = k-1;
// Compute sum of remaining
// subarrays
for (int i = k; i < n; i++)
{
sum = sum + arr[i] - arr[i-k];
if (sum > max_sum)
{
max_sum = sum;
max_end = i;
}
}
// Return starting index
return max_end - k + 1;
}
// Driver program
public static void Main ()
{
int []arr = {1, 12, -5, -6, 50, 3};
int k = 4;
int n = arr.Length;
Console.WriteLine( "The maximum "
+ "average subarray of length "
+ k + " begins at index "
+ findMaxAverage(arr, n, k));
}
}
// This code is contributed by anuj_67.
JavaScript
<script>
// Javascript program to find maximum average
// subarray of given length.
// Returns beginning index of
// maximum average subarray of
// length 'k'
function findMaxAverage(arr, n, k)
{
// Check if 'k' is valid
if (k > n)
return -1;
// Compute sum of first 'k'
// elements
let sum = arr[0];
for (let i = 1; i < k; i++)
sum += arr[i];
let max_sum = sum;
let max_end = k-1;
// Compute sum of remaining
// subarrays
for (let i = k; i < n; i++)
{
sum = sum + arr[i] - arr[i-k];
if (sum > max_sum)
{
max_sum = sum;
max_end = i;
}
}
// Return starting index
return max_end - k + 1;
}
let arr = [1, 12, -5, -6, 50, 3];
let k = 4;
let n = arr.length;
document.write( "The maximum "
+ "average subarray of length "
+ k + " begins at index "
+ findMaxAverage(arr, n, k));
// This code is contributed by suresh07.
</script>
PHP
<?php
// PHP program to find maximum
// average subarray of given length.
// Returns beginning index
// of maximum average
// subarray of length 'k'
function findMaxAverage($arr, $n, $k)
{
// Check if 'k' is valid
if ($k > $n)
return -1;
// Compute sum of first
// 'k' elements
$sum = $arr[0];
for($i = 1; $i < $k; $i++)
$sum += $arr[$i];
$max_sum = $sum;
$max_end = $k-1;
// Compute sum of
// remaining subarrays
for($i = $k; $i < $n; $i++)
{
$sum = $sum + $arr[$i] -
$arr[$i - $k];
if ($sum > $max_sum)
{
$max_sum = $sum;
$max_end = $i;
}
}
// Return starting index
return $max_end - $k + 1;
}
// Driver Code
$arr = array(1, 12, -5, -6, 50, 3);
$k = 4;
$n = count($arr);
echo "The maximum average subarray of ",
"length ", $k , " begins at index "
, findMaxAverage($arr, $n, $k);
// This code is contributed by anuj_67.
?>
OutputThe maximum average subarray of length 4 begins at index 1
Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of elements in the array.
Auxiliary Space: O(1), as we are not using any extra space.
Approach#3: Using sliding window
We can use a sliding window approach to solve this problem, which reduces the time complexity to O(n). We can start by calculating the sum of the first k elements and then move the window one element at a time, subtracting the element that is no longer in the window and adding the new element that is now in the window
Algorithm
1. Initialize a variable max_sum to the sum of the first k elements and max_index to 0.
2. Initialize a variable window_sum to max_sum.
3. Loop through the array from index k to n-1:
a. Subtract the element that is no longer in the window from window_sum.
b. Add the new element that is now in the window to window_sum.
c. If window_sum is greater than max_sum, update max_sum to window_sum and max_index to the starting index of the current window.
4. Return max_index.
C++
#include <iostream>
#include <vector>
using namespace std;
int maxAvgSubarray(vector<int>& arr, int k) {
int n = arr.size(); // Get the length of the array
// Calculate the sum of the first window of size k
int windowSum = 0;
for (int i = 0; i < k; i++) {
windowSum += arr[i];
}
int maxSum = windowSum;
int maxIndex = 0;
// Slide the window and update the maximum sum
for (int i = k; i < n; i++) {
windowSum += arr[i] - arr[i - k];
if (windowSum > maxSum) {
maxSum = windowSum;
maxIndex = i - k + 1;
}
}
return maxIndex;
}
int main() {
vector<int> arr = {1, 12, -5, -6, 50, 3};
int k = 4;
cout << maxAvgSubarray(arr, k) << endl;
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static int maxAvgSubarray(List<Integer> arr, int k) {
int n = arr.size(); // Get the length of the array
// Calculate the sum of the first window of size k
int windowSum = 0;
for (int i = 0; i < k; i++) {
windowSum += arr.get(i);
}
int maxSum = windowSum;
int maxIndex = 0;
// Slide the window and update the maximum sum
for (int i = k; i < n; i++) {
windowSum += arr.get(i) - arr.get(i - k);
if (windowSum > maxSum) {
maxSum = windowSum;
maxIndex = i - k + 1;
}
}
return maxIndex;
}
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(12);
arr.add(-5);
arr.add(-6);
arr.add(50);
arr.add(3);
int k = 4;
System.out.println(maxAvgSubarray(arr, k));
}
}
Python3
def max_avg_subarray(arr, k):
n = len(arr)
window_sum = sum(arr[:k])
max_sum = window_sum
max_index = 0
for i in range(k, n):
window_sum += arr[i] - arr[i-k]
if window_sum > max_sum:
max_sum = window_sum
max_index = i - k + 1
return max_index
arr = [1, 12, -5, -6, 50, 3]
k = 4
print(max_avg_subarray(arr, k))
C#
using System;
using System.Collections.Generic;
namespace MaxAvgSubarrayApp
{
class Program
{
static int MaxAvgSubarray(List<int> arr, int k)
{
int n = arr.Count;// Get the length of the array
int windowSum = 0; // Calculate the sum of the first window of size k
for (int i = 0; i < k; i++)
{
windowSum += arr[i];
}
int maxSum = windowSum;
int maxIndex = 0;
// Slide the window and update the maximum sum
for (int i = k; i < n; i++)
{
windowSum += arr[i] - arr[i - k];
if (windowSum > maxSum)
{
maxSum = windowSum;
maxIndex = i - k + 1;
}
}
return maxIndex;
}
static void Main(string[] args)
{
List<int> arr = new List<int> { 1, 12, -5, -6, 50, 3 };
int k = 4;
Console.WriteLine(MaxAvgSubarray(arr, k));
}
}
}
JavaScript
function max_avg_subarray(arr, k) {
// Get the length of the array
let n = arr.length;
// Calculate the sum of the first window of size k
let window_sum = arr.slice(0, k).reduce((a, b) => a + b, 0);
let max_sum = window_sum;
let max_index = 0;
// Slide the window and update the maximum sum
for (let i = k; i < n; i++) {
window_sum += arr[i] - arr[i - k];
if (window_sum > max_sum) {
max_sum = window_sum;
max_index = i - k + 1;
}
}
return max_index;
}
let arr = [1, 12, -5, -6, 50, 3];
let k = 4;
console.log(max_avg_subarray(arr, k));
Time complexity: O(n) , where n is length of array
Auxiliary Space is O(1).
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 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