Problem Description
Given a 0-indexed integer array nums, for each index i (1 <= i <= nums.length - 2), define the beauty of nums[i] as follows:
- Beauty equals 2 if for every 0 <= j < i and for every i < k <= nums.length - 1, it holds that nums[j] < nums[i] < nums[k].
- Beauty equals 1 if the above condition is not met but nums[i - 1] < nums[i] < nums[i + 1] holds.
- Beauty equals 0 otherwise. The task is to return the sum of the beauty values of all eligible indices.
Key Insights
- Precompute prefix maximums: for each index i store the maximum value from the start up to index i.
- Precompute suffix minimums: for each index i store the minimum value from index i to the end.
- For each eligible index i, check the first condition by comparing nums[i] with the prefix maximum (from i-1) and the suffix minimum (from i+1). If satisfied, add 2.
- Otherwise, check the adjacent condition (nums[i-1] < nums[i] < nums[i+1]) and if satisfied, add 1.
- Use O(n) time and O(n) space to precompute these arrays, ensuring an efficient solution.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n)
Solution
We solve the problem by first precomputing two arrays: prefixMax and suffixMin.
- prefixMax[i] holds the maximum value from index 0 to i.
- suffixMin[i] holds the minimum value from index i to the end of the array.
When iterating through every eligible index (from 1 to nums.length - 2), we check:
- If prefixMax[i-1] < nums[i] < suffixMin[i+1]. If this holds, the beauty is 2.
- Otherwise, if nums[i-1] < nums[i] < nums[i+1] holds, the beauty is 1.
- If neither condition holds, the beauty is 0.
The key trick is the use of precomputed arrays to quickly determine these conditions in constant time for each index, thus reducing the overall complexity per index from O(n) to O(1).