[LeetCode] Beautiful Towers I

2865. Beautiful Towers I

You are given a 0-indexed array maxHeights of n integers.

You are tasked with building n towers in the coordinate line. The ith tower is built at coordinate i and has a height of heights[i].

A configuration of towers is beautiful if the following conditions hold:

  1. 1 <= heights[i] <= maxHeights[i]
  2. heights is a mountain array.

Array heights is a mountain if there exists an index i such that:

  • For all 0 < j <= i, heights[j - 1] <= heights[j]
  • For all i <= k < n - 1, heights[k + 1] <= heights[k]

Return the maximum possible sum of heights of a beautiful configuration of towers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
long long maximumSumOfHeights(vector<int>& A) {
int n = A.size();
long long res = 0;
auto left = [&](long long best, int p) {
long long res = 0;
for(int i = p; i >= 0; i--) {
best = min(best, 1ll * A[i]);
res += best;
}
return res;
};
auto right = [&](long long best, int p) {
long long res = 0;
for(int i = p; i < n; i++) {
best = min(best, 1ll * A[i]);
res += best;
}
return res;
};
for(int i = 0; i < n; i++) {
res = max(res, A[i] + left(A[i],i-1) + right(A[i],i+1));
}
return res;
}
};


Author: Song Hayoung
Link: https://songhayoung.github.io/2023/09/24/PS/LeetCode/beautiful-towers-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.