LeetCode 2234: Maximum Total Beauty of the Gardens
Problem Description
Explanation
To solve this problem, we can follow these steps:
- Initialize variables to keep track of the total beauty, the number of complete gardens, and the minimum number of flowers in any incomplete garden.
- Iterate through the gardens and calculate the total beauty based on the current state.
- Keep planting flowers in the incomplete gardens until we have planted all newFlowers or all gardens are complete.
- Calculate the total beauty based on the final state after planting the flowers.
- Return the maximum total beauty obtained.
Time complexity: O(n) Space complexity: O(1)
Solutions
class Solution {
public int maxTotalBeauty(int[] flowers, int newFlowers, int target, int full, int partial) {
int totalBeauty = 0;
int completeGardens = 0;
int minIncomplete = Integer.MAX_VALUE;
for (int flower : flowers) {
if (flower >= target) {
totalBeauty += full;
completeGardens++;
} else {
minIncomplete = Math.min(minIncomplete, flower);
}
}
int remainingFlowers = newFlowers;
while (remainingFlowers > 0 && minIncomplete < target) {
totalBeauty += partial;
minIncomplete++;
remainingFlowers--;
}
totalBeauty += (Math.min(remainingFlowers, target - minIncomplete)) * partial;
totalBeauty += Math.min(newFlowers, target - minIncomplete - remainingFlowers) * full;
return totalBeauty;
}
}
Loading editor...