# Find maximum average subarray of k length

Given an array with positive and negative numbers, find the maximum average subarray of 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
```

## Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

A Simple Solution is to run two loops. The outer loop picks starting point, the inner loop goes till length ‘k’ from the starting point and computes average of elements. Time complexity of this solution is O(n*k).

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 to arr[i]. Once we have csum[] array with us, we can compute sum between two indexes in O(1) time.
Below is the implementation of this idea. One observation is, a subarray of given length has maximum average if it has maximum sum. So we can avoid floating point arithmetic by just comparing sum.

## CPP

 `// C++ program to find maximum average subarray ` `// of given length. ` `#include ` `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 to arr[i] ` `    ``int` `*csum = ``new` `int``[n]; ` `    ``csum = arr; ` `    ``for` `(``int` `i=1; i 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); ` `    ``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 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. `

## 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 to arr[i] ` `    ``int` `[]csum = ``new` `int``[n]; ` `     `  `    ``csum = arr; ` `    ``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. `

## 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 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 `

## PHP

 ` ``\$n``) ` `        ``return` `-1; ` ` `  `    ``// Create and fill array to ` `    ``// store cumulative sum.  ` `    ``// csum[i] stores sum of  ` `    ``// arr to arr[i] ` `    ``\$csum` `= ``array``(); ` `    ``\$csum`` = ``\$arr``; ` `    ``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. ` `?> `

Output:

`The maximum average subarray of length 4 begins at index 1`

Time Complexity of above solution is O(n), but it requires O(n) auxiliary space.

We can avoid need of extra space by using below Efficient Method.
1) Compute sum of first ‘k’ elements, i.e., elements arr[0..k-1]. Let this sum be ‘sum’. Initialize ‘max_sum’ as ‘sum’
2) Do following for every element arr[i] where i varies from ‘k’ to ‘n-1’
…….a) Remove arr[i-k] from sum and add arr[i], i.e., do sum += arr[i] – arr[i-k]
…….b) If new sum becomes more than max_sum so far, update max_sum.
3) Return ‘max_sum’

## CPP

 `// C++ program to find maximum average subarray ` `// of given length. ` `#include ` `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; ` `    ``for` `(``int` `i=1; i 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); ` `    ``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; ` `        ``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. `

## PHP

 ` ``\$n``) ` `        ``return` `-1; ` ` `  `    ``// Compute sum of first ` `    ``// 'k' elements ` `    ``\$sum` `= ``\$arr``; ` `    ``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. ` `?> `

Output:

`The maximum average subarray of length 4 begins at index 1`

Time complexity of this method is also O(n), but it requires constant extra space.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Improved By : vt_m

Article Tags :
Practice Tags :

5

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.