Sum of Beauty in the Array Problem
Description
LeetCode Problem 2012.
You are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) the beauty of nums[i] equals:
2, ifnums[j] < nums[i] < nums[k], for all0 <= j < iand for alli < k <= nums.length - 1.1, ifnums[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.
Example 1:
Input: nums = [1,2,3]
Output: 2
Explanation: For each index i in the range 1 <= i <= 1:
- The beauty of nums[1] equals 2.
Example 2:
Input: nums = [2,4,6,4]
Output: 1
Explanation: For each index i in the range 1 <= i <= 2:
- The beauty of nums[1] equals 1.
- The beauty of nums[2] equals 0.
Example 3:
Input: nums = [3,2,1]
Output: 0
Explanation: For each index i in the range 1 <= i <= 1:
- The beauty of nums[1] equals 0.
Constraints:
3 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Prefix Maximum and Suffix Minimum
For index i (1 <= i <= n - 2), the beauty is 2 when every element on the left is smaller and every element on the right is larger, that is max(nums[0..i-1]) < nums[i] < min(nums[i+1..]). Otherwise it is 1 if nums[i-1] < nums[i] < nums[i+1], and 0 if neither holds.
Precompute right[i], the minimum of nums[i..n-1], with one backward pass. Then scan forward while keeping l, the maximum of the elements before i, and compare against right[i + 1]. Update l after each step.
Complexity: O(n) time and O(n) space.
class Solution:
def sumOfBeauties(self, nums: List[int]) -> int:
n = len(nums)
right = [nums[-1]] * n
for i in range(n - 2, -1, -1):
right[i] = min(right[i + 1], nums[i])
ans = 0
l = nums[0]
for i in range(1, n - 1):
r = right[i + 1]
if l < nums[i] < r:
ans += 2
elif nums[i - 1] < nums[i] < nums[i + 1]:
ans += 1
l = max(l, nums[i])
return ans