#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool canDistribute(vector<int>& arr, int k, int mid) {
int n = arr.size();
int required = 0;
for (int i = 0; i < n; i++) {
if (arr[i] < mid) {
required += (mid - arr[i]);
}
}
return required >= k;
}
int minimizeMaxElement(vector<int>& arr, int k) {
int n = arr.size();
int low = *max_element(arr.begin(), arr.end()); // The minimum possible answer
int high = low + k; // The maximum possible answer
int result = high;
while (low <= high) {
int mid = low + (high - low) / 2;
if (canDistribute(arr, k, mid)) {
result = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return result;
}
int main() {
vector<int> arr = {7, 5, 1, 9, 1};
int k = 25;
int result = minimizeMaxElement(arr, k);
cout << "Minimum possible maximum element: " << result << endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8YWxnb3JpdGhtPgoKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmJvb2wgY2FuRGlzdHJpYnV0ZSh2ZWN0b3I8aW50PiYgYXJyLCBpbnQgaywgaW50IG1pZCkgewogICAgaW50IG4gPSBhcnIuc2l6ZSgpOwogICAgaW50IHJlcXVpcmVkID0gMDsKCiAgICBmb3IgKGludCBpID0gMDsgaSA8IG47IGkrKykgewogICAgICAgIGlmIChhcnJbaV0gPCBtaWQpIHsKICAgICAgICAgICAgcmVxdWlyZWQgKz0gKG1pZCAtIGFycltpXSk7CiAgICAgICAgfQogICAgfQoKICAgIHJldHVybiByZXF1aXJlZCA+PSBrOwp9CgppbnQgbWluaW1pemVNYXhFbGVtZW50KHZlY3RvcjxpbnQ+JiBhcnIsIGludCBrKSB7CiAgICBpbnQgbiA9IGFyci5zaXplKCk7CiAgICBpbnQgbG93ID0gKm1heF9lbGVtZW50KGFyci5iZWdpbigpLCBhcnIuZW5kKCkpOyAgLy8gVGhlIG1pbmltdW0gcG9zc2libGUgYW5zd2VyCiAgICBpbnQgaGlnaCA9IGxvdyArIGs7ICAvLyBUaGUgbWF4aW11bSBwb3NzaWJsZSBhbnN3ZXIKICAgIGludCByZXN1bHQgPSBoaWdoOwoKICAgIHdoaWxlIChsb3cgPD0gaGlnaCkgewogICAgICAgIGludCBtaWQgPSBsb3cgKyAoaGlnaCAtIGxvdykgLyAyOwoKICAgICAgICBpZiAoY2FuRGlzdHJpYnV0ZShhcnIsIGssIG1pZCkpIHsKICAgICAgICAgICAgcmVzdWx0ID0gbWlkOwogICAgICAgICAgICBoaWdoID0gbWlkIC0gMTsKICAgICAgICB9IGVsc2UgewogICAgICAgICAgICBsb3cgPSBtaWQgKyAxOwogICAgICAgIH0KICAgIH0KCiAgICByZXR1cm4gcmVzdWx0Owp9CgppbnQgbWFpbigpIHsKICAgIHZlY3RvcjxpbnQ+IGFyciA9IHs3LCA1LCAxLCA5LCAxfTsKICAgIGludCBrID0gMjU7CgogICAgaW50IHJlc3VsdCA9IG1pbmltaXplTWF4RWxlbWVudChhcnIsIGspOwogICAgY291dCA8PCAiTWluaW11bSBwb3NzaWJsZSBtYXhpbXVtIGVsZW1lbnQ6ICIgPDwgcmVzdWx0IDw8IGVuZGw7CgogICAgcmV0dXJuIDA7Cn0K