Maximize the Beauty of the Garden Problem
Description
LeetCode Problem 1788.
There is a garden of n flowers, and each flower has an integer beauty value. The flowers are arranged in a line. You are given an integer array flowers of size n and each flowers[i] represents the beauty of the i^th flower.
A garden is valid if it meets these conditions:
- The garden has at least two flowers.
- The first and the last flower of the garden have the same beauty value.
As the appointed gardener, you have the ability to remove any (possibly none) flowers from the garden. You want to remove flowers in a way that makes the remaining garden valid. The beauty of the garden is the sum of the beauty of all the remaining flowers.
Return the maximum possible beauty of some valid garden after you have removed any (possibly none) flowers.
Example 1:
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.
Example 2:
Input: flowers = [100,1,1,-3,1]
Output: 3
Explanation: You can produce the valid garden [1,1,1] to have a total beauty of 1 + 1 + 1 = 3.
Example 3:
Input: flowers = [-1,-2,0,-1]
Output: -2
Explanation: You can produce the valid garden [-1,-1] to have a total beauty of -1 + -1 = -2.
Constraints:
2 <= flowers.length <= 10^5-10^4 <= flowers[i] <= 10^4- It is possible to create a valid garden by removing some (possibly none) flowers.
Solution
Approach: Hash Table + Prefix Sum
The kept flowers must start and end with the same value, and everything in between that is positive can be kept for free (negative flowers in the middle are removed). So for every value we remember its first position in a hash table d, and keep a prefix sum s that counts only positive values.
When a value v shows up again at position i and was first seen at j, the best garden between the two has beauty v + v plus the positive values strictly between them, which is s[i] - s[j + 1]. Take the maximum over all such pairs.
Complexity: time O(n), space O(n), where n is the number of flowers.
from math import inf
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