[LeetCode] Maximize the Beauty of the Garden

1788. Maximize the Beauty of the Garden

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int maximumBeauty(vector<int>& A) {
int n = A.size();
unordered_map<int, pair<int, int>> mp;
vector<int> psum(n + 1);
vector<int> pnegsum(n + 1);
for(int i = 0; i < n; i++) {
if(mp.count(A[i])) mp[A[i]].second = i;
else mp[A[i]] = {i, i};
psum[i + 1] = psum[i] + A[i];
if(A[i] < 0) pnegsum[i + 1] = pnegsum[i] + A[i];
else pnegsum[i + 1] = pnegsum[i];
}

int res = INT_MIN;
for(auto& [_, range] : mp) {
int s = range.first, e = range.second;
if(s == e) continue;
res = max(res, psum[e + 1] - psum[s] - (pnegsum[e] - pnegsum[s + 1]));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/24/PS/LeetCode/maximize-the-beauty-of-the-garden/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.