Skip to main content
Back to problems
#2012
Medium Algorithms

Sum of beauty in the array

Array
51.1% acceptance
Feb 25, 2026
683
78
Given an integer array nums, return an array answer of the same size, where answer[i] equals the beauty of nums[i]. The beauty of nums[i] is: 2 if nums[i] is strictly greater than all elements to its left and strictly less than all elements to its right. 1 if nums[i] > nums[i-1] and nums[i] < nums[i+1]. 0 if none of the above. Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn sum_of_beauties(nums: Vec<i32>) -> i32 {
    let n = nums.len();
    let mut prefix_max = vec![0; n];
    let mut suffix_min = vec![0; n];
    prefix_max[0] = nums[0];
    for i in 1..n { prefix_max[i] = prefix_max[i-1].max(nums[i]); }
    suffix_min[n-1] = nums[n-1];
    for i in (0..n-1).rev() { suffix_min[i] = suffix_min[i+1].min(nums[i]); }
    
    let mut sum = 0;
    for i in 1..n-1 {
      if prefix_max[i-1] < nums[i] && nums[i] < suffix_min[i+1] {
        sum += 2;
      } else if nums[i-1] < nums[i] && nums[i] < nums[i+1] {
        sum += 1;
      }
    }
    sum
  }
}