How to Get Maximum Average Subarray I in C++

  C & C ++ Interview Q&A

Dear readers, today read in this article how to get maximum average subser I in C ++

If you have an array with n elements, then we need to find a contiguous subclass of given length k which has a maximum mean value. We must return the maximum average value.

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

Example for Maximum Average Subarray I in C++

#include <bits/stdc++.h>
using namespace std;
class maxavgProg{
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(){
   maxavgProg ob;
   vector<int> v = {1,13,-5,-8,48,3};
   cout << (ob.findMaxAverage(v, 4));
}

Output

12

LEAVE A COMMENT