HardNo. 1788LeetCode Premium
Maximize the Beauty of the Garden — LeetCode 1788 Python Solution
- Pattern
- Prefix Sum
- Topics
- Greedy, Array, Hash Table, Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 1546 | Maximum Number of Non-Overlapping Subarrays With Sum Equals Target | Medium |
| 0523 | Continuous Subarray Sum | Medium |
| 0525 | Contiguous Array | Medium |
| 0560 | Subarray Sum Equals K | Medium |
| 0621 | Task Scheduler | Medium |
| 0632 | Smallest Range Covering Elements from K Lists | Hard |
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.