Problem Description
Given an array of integers representing the beauty of n flowers arranged in a line, you are allowed to remove any (possibly none) of the flowers. The resulting garden (which is a subsequence of the original) must have at least two flowers and the first and last flower in the subsequence must have the same beauty value. You need to maximize the total beauty (sum) of the resulting valid garden.
Key Insights
- The selected valid garden is a subsequence of the original array with arbitrary removals; order is preserved.
- You must choose two positions (i and j, i < j) such that flowers[i] == flowers[j]. These serve as the fixed start and end of the valid garden.
- For the elements between these two indices, you can pick any subset. Thus, you should only add flowers with positive beauty values, since including negatives would decrease the total sum.
- Precompute a prefix sum array over positive values to quickly compute the sum of all positive beauties in any segment.
- For each unique flower value that appears at least twice, iterate over its indices to compute the maximum achievable beauty using the formula: TotalBeauty = 2 * (flower value) + (sum of positive values between the chosen indices), which can be computed as 2*v + (prefix[j] – prefix[i+1]).
- Use a dictionary (or hash table) to map each flower beauty value to all its indices and then use a greedy scan with maintained minimum prefix value for candidates.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n)
Solution
We first compute a prefix sum array over the input array where each element contributes its value only if it is positive (zero otherwise). This lets us quickly compute the maximum sum we can add from any segment (skipping negatives). Then, for each unique flower value v that appears at least twice, we traverse its sorted indices list. While scanning, maintain the minimum prefix sum at positions corresponding to (index+1) from previous occurrences. For each subsequent occurrence, compute a candidate sum as 2*v (for the two chosen endpoints) plus the difference between the current prefix value and the previously maintained minimum prefix. Take the maximum over all candidates from every flower type as the answer.
Key data structures:
- A prefix sum array over positive values.
- A hash map from flower value to a list of indices (occurrence positions).
Algorithmic approach:
- Build the prefix sum array.
- Build the dictionary mapping each flower value to its list of occurrence indices.
- For each flower value with at least two occurrences, use a greedy two-pointer style scan to compute the best candidate sum.
- Return the maximum candidate sum across all valid flower values.