3
long long maximumBeauty(vector<int> &flowers, long long newFlowers, int target, int full,6
int n = flowers.size();8
sort(flowers.begin(), flowers.end());9
vector<long long> pref(n, 0); // Prefix sums array11
for (int i = 1; i < n; i++) {12
pref[i] = pref[i - 1] + flowers[i];14
for (int i = n; i >= 0; i--) {15
// When i is n, none of the elements are incremented till target.16
if (i < n) { // The ith element(0-indexed) is incremented till target. This is17
// handling the case of "full". We are doing this from the end18
// because it will cost the least number of new Flowers.19
long long toAdd = max(0, target - flowers[i]);20
if (newFlowers < toAdd) {21
break; // We are breaking because we would've already found the best22
// answer in the previous iterations27
long long beautyForFullCase =28
(long long)(n - i) * full; // All the elements from i to n -1 are incremented till target,29
// so they have a beauty of (n - 1) * full31
// Here, we do binary search on x, which is the the maximum number we can32
// increment all the numbers from 0 to i - 1 to. The maximum we can33
// increment to is target-1 because after that, "partial" will not be34
// applicable. Binary search is done to find out the maximum possible35
// answer for the partial case.36
int l = 0, r = target - 1;37
long long beautyForPartialCase = 0;39
long long mid = l + (r - l) / 2; // mid is the maximum number we can increment to40
auto it = upper_bound(flowers.begin(), flowers.end(),41
mid); // will point to an element that is atleast 1 more than the42
// incomplete garden with most number of flowers43
if (it == flowers.begin()) { // there are no incomplete gardens46
long long len = distance(flowers.begin(), it); // number of incomplete gardens47
long long sum = pref[len - 1];48
long long needed = ((long long)mid * len) - sum; // number of flowers needed to make49
// "mid" as the minimum element50
if (needed <= newFlowers) { // if it is possible to plant flowers such that the51
// minimum number of flowers for any garden is52
// "mid", then we go to check for higher values53
// through Binary search55
beautyForPartialCase =56
(long long)mid * partial; // (minimum number of flowers in any incomplete garden)57
// * (partial) = total beauty of incomplete gardens64
max(ans, beautyForFullCase + beautyForPartialCase); // checking if this answer is better65
// than the previous answers computed.