You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/1700-1799/1788.Maximize the Beauty of the Garden/README_EN.md
+57-2
Original file line number
Diff line number
Diff line change
@@ -52,6 +52,14 @@
52
52
53
53
## Solutions
54
54
55
+
**Solution 1: Hash Table + Prefix Sum**
56
+
57
+
We use a hash table $d$ to record the first occurrence of each aesthetic value, and a prefix sum array $s$ to record the sum of the aesthetic values before the current position. If an aesthetic value $v$ appears at positions $i$ and $j$ (where $i \lt j$), then we can get a valid garden $[i+1,j]$, whose aesthetic value is $s[i] - s[j + 1] + v \times 2$. We use this value to update the answer. Otherwise, we record the current position $i$ of the aesthetic value in the hash table $d$. Next, we update the prefix sum. If the aesthetic value $v$ is negative, we treat it as $0$.
58
+
59
+
After traversing all the aesthetic values, we can get the answer.
60
+
61
+
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of flowers.
62
+
55
63
<!-- tabs:start -->
56
64
57
65
### **Python3**
@@ -76,10 +84,11 @@ class Solution:
76
84
```java
77
85
classSolution {
78
86
publicintmaximumBeauty(int[] flowers) {
79
-
int[] s =newint[flowers.length +1];
87
+
int n = flowers.length;
88
+
int[] s =newint[n +1];
80
89
Map<Integer, Integer> d =newHashMap<>();
81
90
int ans =Integer.MIN_VALUE;
82
-
for (int i =0; i <flowers.length; ++i) {
91
+
for (int i =0; i <n; ++i) {
83
92
int v = flowers[i];
84
93
if (d.containsKey(v)) {
85
94
ans =Math.max(ans, s[i] - s[d.get(v) +1] + v *2);
@@ -137,6 +146,52 @@ func maximumBeauty(flowers []int) int {
0 commit comments