This website contains ALL LeetCode **Premium** problems for
**FREE!!**.

All leaked interview problems are collected from Internet.

All leaked interview problems are collected from Internet.

Given an array consisting of `n`

integers, find the contiguous subarray of given length `k`

that has the maximum average value. And you need to output the maximum average value.

**Example 1:**

Input:[1,12,-5,-6,50,3], k = 4Output:12.75Explanation:Maximum average is (12-5-6+50)/4 = 51/4 = 12.75

**Note:**

- 1 <=
`k`

<=`n`

<= 30,000. - Elements of the given array will be in the range [-10,000, 10,000].

b'

\n\n## Solution

\n

\n#### Approach #1 Cumulative Sum [Accepted]

\n

\n#### Approach #2 Sliding Window [Accepted]

\n

\n

'
\n

**Algorithm**

We know that in order to obtain the averages of subarrays with length , we need to obtain the sum of these length subarrays. One of the methods of obtaining this sum is to make use of a cumulative sum array, , which is populated only once. Here, is used to store the sum of the elements of the given array from the first element upto the element at the index.

\nOnce the array has been filled up, in order to find the sum of elements from the index to , all we need to do is to use: . Thus, now, by doing one more iteration over the array, we can determine the maximum average possible from the subarrays of length .

\nThe following animation illustrates the process for a simple example.

\n!?!../Documents/643_Maximum_Average.json:1000,563!?!

\n\n**Complexity Analysis**

- \n
- \n
Time complexity : . We iterate over the array of length once to fill the array. Then, we iterate over elements of to determine the required result.

\n \n - \n
Space complexity : . We make use of a array of length to store the cumulative sum.

\n \n

\n

**Algorithm**

Instead of creating a cumulative sum array first, and then traversing over it to determine the required sum, we can simply traverse over just once, and on the go keep on determining the sums possible for the subarrays of length . To understand the idea, assume that we already know the sum of elements from index to index , say it is .

\nNow, to determine the sum of elements from the index to the index , all we need to do is to subtract the element from and to add the element to . We can carry out our process based on this idea and determine the maximum possible average.

\n\n**Complexity Analysis**

- \n
- \n
Time complexity : . We iterate over the given array of length once only.

\n \n - \n
Space complexity : . Constant extra space is used.

\n \n

\n

Analysis written by: @vinod23

\n