二分答案 + 贪心
AC代码
#include <iostream>
#include <algorithm>
using namespace std;
using LL = long long;
LL tree[1000006];
LL N, M;
bool check(LL h) {
LL s = 0;
for (LL i = 0; i < N; ++i) {
if (tree[i] > h) {
s += tree[i] - h;
}
}
if (s >= M) {
return true;
} else {
return false;
}
}
int main() {
ios::sync_with_stdio(false);
cin >> N >> M;
for (LL i = 0; i < N; ++i) {
cin >> tree[i];
}
LL l = 0, r = 1000000000, mid;
LL ans = -1;
while (l + 1 < r) {
mid = l + (r - l) / 2;
if (check(mid)) {
l = mid;
ans = max(mid, ans);
} else {
r = mid - 1;
}
}
for (LL i = l; i <= r; ++i) {
if (check(i)) {
ans = max(i, ans);
}
}
cout << ans << endl;
}