class Solution {
public:
long long maximumBeauty(vector<int>& flowers, long long newFlowers,
int target, int full, int partial) {
int n = flowers.size();
long long ans = 0LL;
// calculate the rest count of flowers if all planted to target
long long leftFlower = newFlowers;
for (int& flower : flowers) {
flower = min(target, flower);
leftFlower -= max(0, target - flower);
}
// There is no flower need to be planted
if (leftFlower == newFlowers) {
return 1LL * n * full;
}
// be able to planted to all-target
if (leftFlower >= 0) {
return max(1LL * n * full,
1LL * (n - 1) * full + 1LL * (target - 1) * partial);
}
ranges::sort(flowers);
long long presum = 0;
int i, j = 0;
// leftFLower is currently the rest count when all gardens are complete
for (i = 1; i <= n; i++) {
leftFlower += target - flowers[i - 1];
if (leftFlower >= 0) {
while (j < i && 1LL * j * flowers[j] <= presum + leftFlower) {
presum += flowers[j];
j++;
}
if (j > 0) {
ans = max(ans, ((leftFlower + presum) * 1LL / j) * partial + 1LL * (n - i) * full);
}
}
}
return ans;
}
};