Maximum Average Subarray I in C++

C++Server Side ProgrammingProgramming

Suppose we have an array with n elements, we have to find the contiguous subarray of given length k that has the maximum average value. We have to return the maximum average value.

So, if the input is like [1,13,-5,-8,48,3] and k = 4, then the output will be 12.0, as (13-5-8+48)/4 = 12.0.

To solve this, we will follow these steps −

  • sum := 0

  • for initialize i := 0, when i < k, update (increase i by 1), do −

    • sum := sum + nums[i]

  • maxi := sum

  • for initialize i := k, when i < size of nums, update (increase i by 1), do −

    • sum := sum + nums[i] - nums[i - k]

    • if sum > maxi, then −

      • maxi := sum

  • return maxi / k

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   double findMaxAverage(vector<int>& nums, int k) {
      int sum = 0;
      for (int i = 0; i < k; i++) {
         sum += nums[i];
      }
      double maxi = sum;
      for (int i = k; i < nums.size(); i++) {
         sum += nums[i] - nums[i - k];
         if (sum > maxi) {
            maxi = sum;
         }
      }
      return maxi / k;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,13,-5,-8,48,3};
   cout << (ob.findMaxAverage(v, 4));
}

Input

{1,13,-5,-8,48,3}, 4

Output

12
raja
Published on 11-Jun-2020 15:40:10
Advertisements