Problem Description
You are given several gardens with an initial number of flowers in each. You can add up to newFlowers additional flowers. A garden is complete if it has at least target flowers. The total beauty is calculated as:
- (number of complete gardens) * full +
- (minimum number of flowers among incomplete gardens) * partial (if there is any incomplete garden), and your goal is to maximize this total beauty under the constraint of at most newFlowers being planted.
Key Insights
- Sort the gardens to separate those that are already complete (flowers[i] ≥ target) from incomplete ones.
- Cap incomplete gardens’ flower counts at target (i.e. only consider filling them up to target-1, because reaching target makes them complete).
- Use prefix sums on the sorted incomplete gardens to quickly calculate the cost to raise a segment to a certain minimum value.
- Use binary search to determine the highest achievable minimum value for a given number of remaining additional flowers when not turning all gardens complete.
- Iterate over the possible number of gardens to make complete, distributing the remaining newFlowers to maximize the minimum value among the rest.
Space and Time Complexity
Time Complexity: O(n log n)
Space Complexity: O(n)
Solution
The approach starts by sorting the gardens and separating those that already have target or more flowers from the incomplete ones. For the incomplete ones, we cap the flower count to target-1 because any garden reaching target becomes complete and should be considered separately.
A prefix sum array is built for the incomplete gardens to allow efficient queries of the cost to raise gardens to a particular minimum level. Then, for each possible count of gardens we might turn to complete (by investing enough newFlowers), we use binary search to determine the maximum possible minimum value that can be achieved among the remaining incomplete gardens. We compute the total required newFlowers using the prefix sum array and check feasibility.
By iterating over all possibilities (making 0 to all incomplete gardens complete) and also considering the case when all gardens are complete, we keep track of the maximum total beauty.
This solution uses sorting, prefix sums, and binary search as the main techniques, along with some greedy choices in distribution.