[LeetCode] Sum of Beauty in the Array

2012. Sum of Beauty in the Array

You are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) the beauty of nums[i] equals:

  • 2, if nums[j] < nums[i] < nums[k], for all 0 <= j < i and for all i < k <= nums.length - 1.
  • 1, if nums[i - 1] < nums[i] < nums[i + 1], and the previous condition is not satisfied.
  • 0, if none of the previous conditions holds.

Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int sumOfBeauties(vector<int>& A) {
int res = 0, n = A.size();
vector<int> l(n), r(n);
for(int i = 1, ma = A[0]; i < n; i++) {
l[i] = ma;
ma = max(ma, A[i]);
}
for(int i = n - 2, mi = A[n - 1]; i >= 0; i--) {
r[i] = mi;
mi = min(mi, A[i]);
}
for(int i = 1; i <= n - 2; i++) {
if(l[i] < A[i] and A[i] < r[i]) res += 2;
else if(A[i-1] < A[i] and A[i] < A[i+1]) res += 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/23/PS/LeetCode/sum-of-beauty-in-the-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.