
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum Average Subarray II in C++
Suppose we have an array with n integers, we have to find the contiguous subarray whose length is greater than or equal to k that has the maximum average value. We have to find the maximum average value.
So, if the input is like [1,12,-5,-6,50,3], k = 4, then the output will be 12.75, as when length is 5, maximum average value is 10.8, when length is 6, maximum average value is 9.16667. Thus output is 12.75.
To solve this, we will follow these steps −
Define a function ok(), this will take x, an array nums, k,
n := size of nums
Define an array arr of size: n.
-
for initialize i := 0, when i < n, update (increase i by 1), do −
arr[i] := nums[i] - x
sum := 0, last := 0
-
for initialize i := 0, when i < k, update (increase i by 1), do −
sum := sum + arr[i]
-
if sum >= 0, then −
return true
-
for initialize i := 0, j := k, when j < n, update (increase i by 1), (increase j by 1), do −
last := last + arr[i]
sum := sum + arr[j]
-
if last < 0, then −
sum := sum - last
last := 0
-
if sum >= 0, then −
return true
return false
From the main method do the following −
ret := 0, low := -inf, high := inf
-
while high - low > 10^-5, do
mid := low + (high - low) / 2
-
if ok(mid, nums, k) is true, then −
low := mid
ret := mid
-
Otherwise
high := mid
return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: bool ok(double x, vector <int>& nums, int k){ int n = nums.size(); double arr[n]; for (int i = 0; i < n; i++) { arr[i] = nums[i] - x; } double sum = 0; double last = 0; for (int i = 0; i < k; i++) { sum += arr[i]; } if (sum >= 0) return true; for (int i = 0, j = k; j < n; i++, j++) { last += arr[i]; sum += arr[j]; if (last < 0) { sum -= last; last = 0; } if (sum >= 0) return true; } return false; } double findMaxAverage(vector<int>& nums, int k) { double ret = 0; double low = INT_MIN; double high = INT_MAX; while (high - low > 1e-5) { double mid = low + (high - low) / 2; if (ok(mid, nums, k)) { low = mid; ret = mid; } else { high = mid; } } return ret; } }; main(){ Solution ob; vector<int> v = {1,12,-5,-6,50,3}; cout << (ob.findMaxAverage(v, 4)); }
Input
{1,12,-5,-6,50,3},4
Output
12.75000