Maximize the Beauty of the Garden — LeetCode 1788 Python Solution

HardLeetCode PremiumGreedyArrayHash TablePrefix Sum
Problem
#1788
Pattern
Prefix Sum
Reading time
2 min

The problem

There is a garden of n flowers, and each flower has an integer beauty value. The flowers are arranged in a line.

Example

Input
flowers = [1,2,3,1,2]
Output
8
Explanation
You can produce the valid garden [2,3,1,2] to have a total beauty of 2 + 3 + 1 + 2 = 8.

Python solution

Python
class Solution:
    def maximumBeauty(self, flowers: List[int]) -> int:
        s = [0] * (len(flowers) + 1)
        d = {}
        ans = -inf
        for i, v in enumerate(flowers):
            if v in d:
                ans = max(ans, s[i] - s[d[v] + 1] + v * 2)
            else:
                d[v] = i
            s[i + 1] = s[i] + max(v, 0)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1788. Maximize the Beauty of the Garden 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 1788. Maximize the Beauty of the Garden?
LeetCode 1788. Maximize the Beauty of the Garden is rated Hard on LeetCode.
What is the time complexity of LeetCode 1788. Maximize the Beauty of the Garden?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1788. Maximize the Beauty of the Garden?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1788. Maximize the Beauty of the Garden cover?
LeetCode 1788. Maximize the Beauty of the Garden is tagged Greedy, Array, Hash Table and Prefix Sum on LeetCode.
Is LeetCode 1788. Maximize the Beauty of the Garden a premium problem?
Yes. LeetCode 1788. Maximize the Beauty of the Garden is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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