LeetCode每日一题(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.

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 <= 105
  • 1 <= nums[i] <= 105

这题的要点是别想复杂了, 题目怎么说的怎么做就好, 别想着整花活。

我们建立两个数组 prefix 和 suffix 使得 prefix[i]为 nums[i]左侧的最大值, suffix[i]为 nums[i]右侧的最小值, 这样如果 prefix[i-1] < nums[i] < suffix[i+1], 则我们符合第一种情况, 分值+2, 如果不符合这一条件, 我们则退而求其次, 检查 nums[i-1] < nums[i] < nums[i+1], 如果成立则符合第二种情况, 分值+1, 如果这两种都不符合则分值+0



impl Solution {
    pub fn sum_of_beauties(nums: Vec<i32>) -> i32 {
        let prefix: Vec<i32> = nums
            .iter()
            .scan(0, |max, n| {
                *max = (*max).max(*n);
                Some(*max)
            })
            .collect();
        let mut suffix: Vec<i32> = nums
            .iter()
            .rev()
            .scan(i32::MAX, |min, n| {
                *min = (*min).min(*n);
                Some(*min)
            })
            .collect();
        suffix.reverse();
        let mut ans = 0;
        for i in 1..nums.len() - 1 {
            if prefix[i - 1] < nums[i] && nums[i] < suffix[i + 1] {
                ans += 2;
                continue;
            }
            if nums[i - 1] < nums[i] && nums[i] < nums[i + 1] {
                ans += 1;
            }
        }
        ans
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值