# Find maximum average subarray of k length in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of size n consisting of positive and negative values and an integer k. Our task is to find the maximum average subarray of k length.

Let’s take an example to understand the problem,

Input: arr[] = {4, -1, 5, 6, -2, 4} k = 3

Output: 10

Explanation:

The subarray of size 3 with max sum is -1, 5, 6 = 10

## Solution Approach

A solution to the problem is done by using an auxiliary array to store cumulative sum till the current index in the array.

To find the sum of subarrays, we need to compute the difference between the indices of the positions of the subarray.

## Example

Live Demo

#include<bits/stdc++.h>
using namespace std;

int findMaxSubArrayAverage(int arr[], int n, int k) {
if (k > n)
return -1;

int *auxSumArray = new int[n];
auxSumArray[0] = arr[0];
for (int i=1; i<n; i++)
auxSumArray[i] = auxSumArray[i-1] + arr[i];
int maxSum = auxSumArray[k-1], subEndIndex = k-1;

for (int i=k; i<n; i++) {

int sumVal = auxSumArray[i] - auxSumArray[i-k];
if (sumVal > maxSum) {

maxSum = sumVal;
subEndIndex = i;
}
}

return subEndIndex - k + 1;
}

int main() {

int arr[] = {4, -1, 5, 6, -2, 4};
int k = 3;
int n = sizeof(arr)/sizeof(arr[0]);
cout<<"The maximum average subarray of length "<<k<<" begins at index "<<findMaxSubArrayAverage(arr, n, k);
return 0;
}

## Output

The maximum average subarray of length 3 begins at index 1
Published on 25-Jan-2021 05:20:58
Advertisements