Sum of Beauty in the Array - Problem
You're tasked with calculating the "beauty score" of elements in an array based on how well they fit into their surroundings!
Given a 0-indexed integer array nums, you need to determine the beauty value for each element at index i where 1 โค i โค nums.length - 2 (excluding the first and last elements).
The beauty rules are:
- Beauty = 2: If
nums[i]is globally beautiful - meaning all elements to its left are smaller AND all elements to its right are larger - Beauty = 1: If
nums[i]is locally beautiful - meaning only its immediate neighbors satisfynums[i-1] < nums[i] < nums[i+1] - Beauty = 0: If neither condition is met
Your goal is to return the sum of all beauty values for the valid indices.
Example: For [1,5,3,6,1], element 5 at index 1 has beauty 1 (locally beautiful), element 3 at index 2 has beauty 0, and element 6 at index 3 has beauty 0. Total sum = 1.
Input & Output
example_1.py โ Basic Array
$
Input:
[1,5,3,6,1]
โบ
Output:
0
๐ก Note:
For index 1 (value 5): Not globally beautiful since 5 > 3. Not locally beautiful since 5 > 3. Beauty = 0. For index 2 (value 3): Not globally beautiful since 5 > 3. Not locally beautiful since 5 > 3. Beauty = 0. For index 3 (value 6): Not globally beautiful since 6 > 1. Not locally beautiful since 6 > 1. Beauty = 0. Total = 0.
example_2.py โ Mixed Beauty Values
$
Input:
[1,4,6,7,1]
โบ
Output:
4
๐ก Note:
For index 1 (value 4): leftMax[1]=1 < 4 and 4 < rightMin[1]=1? No. Local: 1 < 4 < 6? Yes. Beauty = 1. For index 2 (value 6): leftMax[2]=4 < 6 and 6 < rightMin[2]=1? No. Local: 4 < 6 < 7? Yes. Beauty = 1. For index 3 (value 7): leftMax[3]=6 < 7 and 7 < rightMin[3]=1? No. Local: 6 < 7 < 1? No. Beauty = 0. Total = 2.
example_3.py โ Global Beauty Case
$
Input:
[1,2,3,4,5]
โบ
Output:
6
๐ก Note:
This is a strictly increasing array. Index 1 (value 2): leftMax[1]=1 < 2 < rightMin[1]=3. Beauty = 2. Index 2 (value 3): leftMax[2]=2 < 3 < rightMin[2]=4. Beauty = 2. Index 3 (value 4): leftMax[3]=3 < 4 < rightMin[3]=5. Beauty = 2. Total = 2 + 2 + 2 = 6.
Constraints
- 3 โค nums.length โค 105
- 1 โค nums[i] โค 105
- Only middle elements are considered (indices 1 to n-2)
Visualization
Tap to expand
Understanding the Visualization
1
Survey Left Boundary
Record the highest peak seen when approaching from the left
2
Survey Right Boundary
Record the lowest peak seen when approaching from the right
3
Assess Global Beauty
Peak gets score 2 if it's higher than all left peaks and lower than all right peaks
4
Check Local Beauty
If not globally beautiful, check if peak is higher than immediate neighbors (score 1)
5
Sum Total Beauty
Add up all beauty scores across the mountain range
Key Takeaway
๐ฏ Key Insight: Pre-calculating left maximums and right minimums transforms an O(nยฒ) nested loop problem into an elegant O(n) solution with just three linear passes through the data.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code