Approach
Sorting and greedy selection
For Maximum Total Beauty of the Gardens, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 49 lines of Python from the credited upstream file 2234.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def maximumBeauty(3 self,4 flowers: list[int],5 newFlowers: int,6 target: int,7 full: int,8 partial: int,9 ) -> int:10 n = len(flowers)11 12 13 flowers = [min(flower, target) for flower in flowers]14 flowers.sort()15 16 17 if flowers[0] == target:18 return n * full19 20 21 if newFlowers >= n * target - sum(flowers):22 return max(n * full, (n - 1) * full + (target - 1) * partial)23 24 ans = 025 leftFlowers = newFlowers26 27 cost = [0] * n28 29 for i in range(1, n):30 31 cost[i] = cost[i - 1] + i * (flowers[i] - flowers[i - 1])32 33 i = n - 1 34 while flowers[i] == target:35 i -= 136 37 while leftFlowers >= 0:38 39 40 41 42 j = min(i + 1, bisect_right(cost, leftFlowers))43 minIncomplete = flowers[j - 1] + (leftFlowers - cost[j - 1]) j44 ans = max(ans, (n - 1 - i) * full + minIncomplete * partial)45 leftFlowers -= max(0, target - flowers[i])46 i -= 147 48 return ans49