![]() |
VOOZH | about |
You are given an array of n-elements you have to find the mean of the array as mean of all consecutive m-elements of array for all possible m-length array with consecutive elements.
Examples:
Input :arr[] = {3, 5, 1, 8, 9, 4},
m = 4
Output : Mean = 5.16667
Explanation : {3, 5, 1, 8}, {5, 1, 8, 9},
{1, 8, 9, 4} are three set of m-consecu-
tive elements. Mean of mean of sets
is (17/4 + 23/4 + 22/4 )/ 3
Input : arr[] = {9, 4}, m = 1
Output : Mean = 6.5
Explanation : {9}, {4} are two set of
1-consecutive element. Mean of means
of sets is (9 + 4 )/ 2
Naive approach: A simple solution is to consider all subarrays of size m, compute their means. Finally, return mean of means.
An efficient solution is to use the Sliding Window Algorithm for this problem where we find sum of m-length window and then add up mean of each window to a value sum. At last, we will have our result by dividing total sum by number of window possible and that too is sum /(n-m+1).
Mean = 4.9375
Time Complexity: O(N)
Auxiliary Space: O(1)