@@ -9,51 +9,18 @@ using namespace std;
9
9
class Solution
10
10
{
11
11
public:
12
- struct range
13
- {
14
- int value;
15
- int start;
16
- mutable int end;
17
- mutable int sum;
18
- bool operator <(const range &b) {
19
- return this ->sum > b.sum ;
20
- }
21
-
22
- bool operator ==(int b) {
23
- return this ->value == b;
24
- }
25
- };
26
-
27
12
int maximumBeauty (vector<int > &flowers) {
28
13
int n = flowers.size ();
29
- vector<range> ranges ;
30
- vector< int > sum (n + 1 , 0 ) ;
14
+ unordered_map< int , int > hash ;
15
+ int mx = INT_MIN, sum = 0 ;
31
16
32
17
for (int i = 0 ; i < n; ++i) {
33
18
int beauty = flowers[i];
34
- sum[i + 1 ] = sum[i] + beauty;
35
- auto r = find (ranges.begin (), ranges.end (), beauty);
36
- if (r == ranges.end ()) {
37
- ranges.push_back ({beauty, i, -1 });
38
- } else {
39
- r->end = i;
40
- r->sum = sum[i + 1 ] - sum[r->start ];
41
- }
42
- }
43
-
44
- sort (ranges.begin (), ranges.end ());
45
-
46
- int mx = INT_MIN;
47
- for (auto r : ranges) {
48
- if (r.end == -1 )
49
- continue ;
50
- int local = r.sum ;
51
- for (auto i = r.start + 1 ; i <= r.end - 1 ; ++i) {
52
- if (flowers[i] < 0 ) {
53
- local = local - flowers[i];
54
- }
19
+ mx = hash.find (beauty) == hash.end () ? mx : max (mx, sum - hash[beauty] + 2 * beauty);
20
+ sum += beauty > 0 ? beauty : 0 ;
21
+ if (hash.find (beauty) == hash.end ()) {
22
+ hash[beauty] = sum;
55
23
}
56
- mx = max (local, mx);
57
24
}
58
25
59
26
return mx;
0 commit comments