
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Maximum average of a subarray of size of at least X and at most Y in C++
Problem statement
Given an array arr[] and two integers X and Y. The task is to find a sub-array of size of at least X and at most Y with the maximum average
Example
If input array is {2, 10, 15, 7, 8, 4} and x = 3 and Y = 3 then we can obtain maximum average 12.5 as follows −
(10 + 15) / 2 = 12.5
Algorithm
- Iterate over every sub-array of size starting from X to size Y and find the maximum average among all such sub-arrays.
- To reduce the time complexity, we can use prefix sum array to get the sum of any sub-array in O(1) complexity
Example
Let us now see an example −
#include <bits/stdc++.h> using namespace std; double getMaxAverage(int *arr, int n, int x, int y) { int prefix[n]; prefix[0] = arr[0]; for (int i = 1; i < n; ++i) { prefix[i] = prefix[i - 1] + arr[i]; } double maxAverage = 0; for (int i = 0; i < n; ++i) { for (int j = i + x - 1; j < i + y && j < n; ++j) { double sum = prefix[j]; if (i > 0) { sum = sum - prefix[i - 1]; double current = sum / double(j - i + 1); maxAverage = max(maxAverage,current); } } } return maxAverage; } int main() { int arr[] = {2, 10, 15, 7, 8, 4}; int x = 2; int y = 3; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum average = " << getMaxAverage(arr, n, x, y) << endl; return 0; }
Output
Maximum average = 12.5
- Related Articles
- Maximum sum subarray removing at most one element in C++
- Maximum subarray sum by flipping signs of at most K array elements in C++
- Maximum Subarray Sum after inverting at most two elements in C++
- Program to find largest average of sublist whose size at least k in Python
- Maximize the maximum subarray sum after removing at most one element in C++
- Find maximum average subarray of k length in C++
- Shortest Subarray with Sum at Least K in C++
- Maximum average of a specific length of subarray in JavaScript
- Maximum Average Subarray I in C++
- Maximum Average Subarray II in C++
- Largest sum subarray with at-least k numbers in C++
- Find maximum (or minimum) sum of a subarray of size k in C++
- Maximum Unique Element in every subarray of size K in c++
- Maximum number of fixed points using at most 1 swaps in C++
- Get at least x number of rows in MySQL?

Advertisements