The "Sum of Beauty in the Array" problem asks you to calculate a "beauty score" for each element nums[i] in an array (where ) based on its relationship with the rest of the array.
nums[i] is strictly greater than all elements to its left AND strictly smaller than all elements to its right.nums[i-1] < nums[i] < nums[i+1].i.Amazon frequently uses this problem to test a candidate's ability to handle array-wide constraints efficiently. The "Score 2" condition requires knowing the maximum value to the left and the minimum value to the right of every element. It's a classic problem for teaching the concept of "Pre-processing" and "Auxiliary Arrays" to avoid redundant nested loops.
The pattern used is Pre-computation using Prefix Maximums and Suffix Minimums.
max_left where max_left[i] is the maximum of all elements from 0 to i-1.min_right where min_right[i] is the minimum of all elements from i+1 to n-1.i = 1 to n-2 and check:
max_left[i] < nums[i] < min_right[i], add 2.nums[i-1] < nums[i] < nums[i+1], add 1.Array: [1, 2, 3]
[2, 4, 6, 3]i, re-scanning the entire left and right side to find the max and min. This results in an O(N²) solution.i=1 to n-2. Forgetting the constraints on i can lead to errors.Any time you need to compare an element against "all elements to the left" or "all elements to the right," your mind should immediately jump to pre-computing prefix/suffix arrays. This is a very common technique for optimizing array problems.