Maximum Total Beauty of the Gardens — LeetCode 2234 Python Solution

HardGreedyArrayTwo PointersBinary SearchEnumerationPrefix SumSorting
Problem
#2234
Pattern
Prefix Sum
Reading time
5 min

The problem

Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden.

Example

Input
flowers = [1,3,1,1], newFlowers = 7, target = 6, full = 12, partial = 1
Output
14
Explanation
Alice can plant

Python solution

Python
class Solution:
    def maximumBeauty(
        self, flowers: List[int], newFlowers: int, target: int, full: int, partial: int
    ) -> int:
        flowers.sort()
        n = len(flowers)
        s = list(accumulate(flowers, initial=0))
        ans, i = 0, n - bisect_left(flowers, target)
        for x in range(i, n + 1):
            newFlowers -= 0 if x == 0 else max(target - flowers[n - x], 0)
            if newFlowers < 0:
                break
            l, r = 0, n - x - 1
            while l < r:
                mid = (l + r + 1) >> 1
                if flowers[mid] * (mid + 1) - s[mid + 1] <= newFlowers:
                    l = mid
                else:
                    r = mid - 1
            y = 0
            if r != -1:
                cost = flowers[l] * (l + 1) - s[l + 1]
                y = min(flowers[l] + (newFlowers - cost) // (l + 1), target - 1)
            ans = max(ans, x * full + y * partial)
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2234. Maximum Total Beauty of the Gardens is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2234. Maximum Total Beauty of the Gardens?
LeetCode 2234. Maximum Total Beauty of the Gardens is rated Hard on LeetCode.
What is the time complexity of LeetCode 2234. Maximum Total Beauty of the Gardens?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2234. Maximum Total Beauty of the Gardens?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2234. Maximum Total Beauty of the Gardens cover?
LeetCode 2234. Maximum Total Beauty of the Gardens is tagged Greedy, Array, Two Pointers, Binary Search, Enumeration, Prefix Sum and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview