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 beauty 2: all left [1] < 2 < all right [3] ✓. Beauty = 2. Sum = 2.
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: 1
💡 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 the Array INPUT nums = [1, 2, 3] 1 i=0 2 i=1 3 i=2 Check indices 1 to n-2 (Only i=1 for this array) Beauty Rules: Beauty = 2: All left < nums[i] < All right Beauty = 1: nums[i-1] < nums[i] < nums[i+1] Beauty = 0: Neither condition holds ALGORITHM STEPS 1 Precompute Prefix Max prefixMax[i] = max of 0..i-1 prefixMax = [-, 1, 2] 2 Precompute Suffix Min suffixMin[i] = min of i+1..n-1 suffixMin = [2, 3, -] 3 Check i=1 (nums[1]=2) prefixMax[1]=1 < 2 < suffixMin[1]=3 1 < 2 < 3 --> OK! 4 Assign Beauty All left < 2 < All right beauty[1] = 2 Time: O(n) | Space: O(n) Single pass with precomputation FINAL RESULT Beauty values for each index: N/A i=0 2 i=1 N/A i=2 Sum of Beauty = beauty[1] = 2 Output: 2 OK - Matches Expected Only i=1 contributes Key Insight: Use prefix maximum and suffix minimum arrays to check the "strictly greater than all left" and "strictly less than all right" conditions in O(1) time per index. This avoids nested loops and achieves O(n) time complexity. Check beauty=2 condition first, then fall back to beauty=1. TutorialsPoint - Sum of Beauty in the Array | Optimal Solution
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