原文链接: https://leetcode-cn.com/problems/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, ifnums[j] < nums[i] < nums[k], for all0 <= j < iand for alli < k <= nums.length - 1.1, ifnums[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.
Example 1:
Input: nums = [1,2,3] Output: 2 Explanation: For each index i in the range 1 <= i <= 1: - The beauty of nums[1] equals 2.
Example 2:
Input: nums = [2,4,6,4] Output: 1 Explanation: For each index i in the range 1 <= i <= 2: - The beauty of nums[1] equals 1. - The beauty of nums[2] equals 0.
Example 3:
Input: nums = [3,2,1] Output: 0 Explanation: For each index i in the range 1 <= i <= 1: - The beauty of nums[1] equals 0.
Constraints:
3 <= nums.length <= 1051 <= nums[i] <= 105
中文题目
给你一个下标从 0 开始的整数数组 nums 。对于每个下标 i(1 <= i <= nums.length - 2),nums[i] 的 美丽值 等于:
2,对于所有0 <= j < i且i < k <= nums.length - 1,满足nums[j] < nums[i] < nums[k]1,如果满足nums[i - 1] < nums[i] < nums[i + 1],且不满足前面的条件0,如果上述条件全部不满足
返回符合 1 <= i <= nums.length - 2 的所有 nums[i] 的 美丽值的总和 。
示例 1:
输入:nums = [1,2,3] 输出:2 解释:对于每个符合范围 1 <= i <= 1 的下标 i : - nums[1] 的美丽值等于 2
示例 2:
输入:nums = [2,4,6,4] 输出:1 解释:对于每个符合范围 1 <= i <= 2 的下标 i : - nums[1] 的美丽值等于 1 - nums[2] 的美丽值等于 0
示例 3:
输入:nums = [3,2,1] 输出:0 解释:对于每个符合范围 1 <= i <= 1 的下标 i : - nums[1] 的美丽值等于 0
提示:
3 <= nums.length <= 1051 <= nums[i] <= 105
通过代码
高赞题解
好像接雨水的挡板问题,美丽值就是左边最大值比自己小,右边最小值比自己大
class Solution {
public:
int sumOfBeauties(vector<int>& nums) {
int n = nums.size();
vector<int> l_max(n, INT_MIN); l_max[0] = nums[0]; // 某元素左边最大元素
vector<int> r_min(n, INT_MAX); r_min[n-2] = nums[n-1]; // 某元素右边最小元素
for (int i = 1; i < n; ++i) {
l_max[i] = max( l_max[i-1], nums[i-1] );
}
for (int i = n-2; i >= 0; --i) {
r_min[i] = min( r_min[i+1], nums[i+1] );
}
int ans = 0;
for (int i = 1; i < n-1; ++i) {
if (nums[i] > l_max[i] && nums[i] < r_min[i]) ans += 2;
else if (nums[i] > nums[i-1] && nums[i] < nums[i+1]) ++ans;
}
return ans;
}
};
统计信息
| 通过次数 | 提交次数 | AC比率 |
|---|---|---|
| 4425 | 12183 | 36.3% |
提交历史
| 提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
|---|