Sum of Beauty in the Array - Problem

You are given a 0-indexed integer array nums. For each index i (where 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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3]
Output: 2
💡 Note: Only middle element is nums[1] = 2. Check: nums[0] < nums[1] < nums[2] → 1 < 2 < 3 ✓. Beauty = 1. Sum = 1.
Example 2 — Multiple Elements
$ Input: nums = [2,4,6,4]
Output: 1
💡 Note: Middle elements: nums[1] = 4, nums[2] = 6. nums[1]: 2 < 4 < 6 ✓ (beauty 1). nums[2]: 4 < 6 > 4 ✗ (beauty 0). Sum = 1 + 0 = 1.
Example 3 — Maximum Beauty
$ Input: nums = [3,2,4,2,4]
Output: 4
💡 Note: nums[1] = 2: all left [3] > 2 ✗, neighbors 3 > 2 < 4 ✗ (beauty 0). nums[2] = 4: all left [3,2] < 4 ✓, all right [2,4] ≤ 4 ✗, neighbors 2 < 4 > 2 ✗ (beauty 0). nums[3] = 2: neighbors 4 > 2 < 4 ✓ (beauty 1). Sum = 0 + 0 + 1 = 1.

Constraints

  • 3 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Sum of Beauty in Array: [1,2,3]123index 0index 1index 2Check middle element nums[1] = 2Beauty 2: all left < 2 < all right? 1 < 2 < 3 ✓Beauty = 2 (maximum beauty)Total Sum = 2
Understanding the Visualization
1
Input Array
Array with elements to check for beauty
2
Beauty Calculation
Check each middle element for beauty conditions
3
Sum Result
Total sum of all beauty values
Key Takeaway
🎯 Key Insight: Pre-compute prefix maximums and suffix minimums to check beauty conditions in O(1) time per element
Asked in
Google 25 Microsoft 18
32.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen