#2234

Maximum Total Beauty of the Gardens

Hard
ArrayTwo PointersBinary SearchGreedySortingEnumerationPrefix SumGreedySortingTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal approach uses a greedy strategy to maximize the number of complete gardens first, then calculates the beauty based on the remaining flowers. This is efficient and leverages sorting to prioritize gardens.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the gardens based on the number of flowers already planted.
  2. 2Step 2: Iterate through the sorted list, attempting to make as many gardens complete as possible with the available newFlowers.
  3. 3Step 3: For each garden made complete, subtract the required flowers from newFlowers and update the count of complete gardens.
  4. 4Step 4: Calculate the minimum number of flowers in incomplete gardens and compute the total beauty.
solution.py16 lines
1def maxBeautyOptimal(flowers, newFlowers, target, full, partial):
2    flowers.sort()
3    complete_gardens = 0
4    n = len(flowers)
5    for i in range(n):
6        if flowers[i] < target:
7            needed = target - flowers[i]
8            if newFlowers >= needed:
9                newFlowers -= needed
10                complete_gardens += 1
11            else:
12                flowers[i] += newFlowers
13                break
14    incomplete_min = min((flowers[i] for i in range(n) if flowers[i] < target), default=0)
15    beauty = complete_gardens * full + (incomplete_min * partial if complete_gardens < n else 0)
16    return beauty

Complexity note: The time complexity is O(n log n) due to the sorting step, and the space complexity is O(1) since we are using a constant amount of extra space.

  • 1Greedy strategies often yield optimal results in resource allocation problems.
  • 2Sorting helps prioritize which gardens to complete first.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.