Find maximum average subarray of k length - GeeksforGeeks
Given an array with positive and negative numbers, find the maximum average subarray of given length.
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’
Read full article from Find maximum average subarray of k length - GeeksforGeeks
Given an array with positive and negative numbers, find the maximum average subarray of given length.
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[0] to arr[i]. Once we have csum[] array with us, we can compute sum between two indexes in O(1) time.
// 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;
}
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’
// 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++)
{
int
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;
}