Maximize the Beauty of the Garden - Problem
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 ith 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.
Input & Output
Example 1 — Basic Case
$
Input:
flowers = [1,3,2,1,4]
›
Output:
8
💡 Note:
We can create a valid garden using flowers at indices 0 and 3 (both have beauty 1). The garden includes flowers [1,3,2,1] with total beauty = 1+3+2+1 = 7. Actually, we want the maximum, so we check all possibilities and find that keeping [1,3,2,1] gives us 7.
Example 2 — Multiple Options
$
Input:
flowers = [2,4,2,4]
›
Output:
12
💡 Note:
We have two options: garden with first/last flower = 2 gives sum 2+4+2+4 = 12, or garden with flowers at indices 1,3 (value 4) gives sum 4+2+4 = 10. Maximum is 12.
Example 3 — No Valid Garden
$
Input:
flowers = [1,2,3,4]
›
Output:
0
💡 Note:
No two flowers have the same beauty value, so we cannot create a valid garden. Return 0.
Constraints
- 2 ≤ flowers.length ≤ 104
- -104 ≤ flowers[i] ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of flower beauty values
2
Find Matches
Identify flowers that can serve as valid boundaries
3
Calculate Segments
Find maximum sum between matching boundaries
Key Takeaway
🎯 Key Insight: Find all segments where first and last flowers have the same beauty value, then return the maximum sum among all such valid segments.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code