A. Beautiful Average
Problem Statement
You are given an array of length .
Your task is to find the maximum possible average value of any subarray* of the array .
Formally, for any indices such that , define the average of the subarray as the sum of elements divided by the number of elements or:
Output the maximum value of over all choices of .
*A subarray is a contiguous part of an array.
Solution
The problem asks for the maximum average value of any subarray. Let’s consider a subarray of length 1, which consists of a single element . The average of this subarray is simply .
Let the maximum element in the array be . If we form a subarray of length 1 with this element, the average is . Can we get a better average?
Consider any subarray containing the maximum element . If we add any other element to this subarray, the new element will be less than or equal to . Therefore, the average of the new, larger subarray will not be greater than .
For example, if we have a subarray with elements , the average is . If we add an element , the new average will be . It can be shown that this new average will not exceed the original average if the added element is less than or equal to the original average. Since we know the maximum element is , any subarray containing and other elements will have an average at most .
Therefore, the maximum possible average is achieved by a subarray of length 1, consisting of the maximum element in the array. The problem is reduced to finding the maximum value in the given array.
View Code
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <set>
#include <tuple>
#include <map>
#include <vector>
using namespace std;
#define int long long
// #define mod 1000000007
#define N 500005
void solve() {
int n;
cin >> n;
vector<int> a(n);
int ans = INT32_MIN;
for (int i = 0; i < n; i++) {
cin >> a[i];
ans= max(ans,a[i]);
}
cout << ans << endl;
}
int32_t main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
#ifdef DEBUG
freopen("./input.txt", "r", stdin);
#endif
int t;
cin >> t;
while (t--) {
#ifdef DEBUG
static int test_num = 1;
cout << "test case: " << test_num++ << endl;
#endif
solve();
}
}