Problem Description
Given an integer array nums of length n, for each contiguous subarray of size k, compute its beauty. The beauty of a subarray is defined as the xth smallest negative integer in that subarray; if the subarray contains fewer than x negative numbers, the beauty is 0.
Key Insights
- Use a sliding window of size k.
- Since we only care about negative numbers (range between -50 and -1), maintain their frequency count in the current window.
- For each window, iterate over possible negative numbers (from -50 to -1) in order to determine the xth smallest negative.
- Update the frequency count when sliding the window (remove the outgoing element and add the incoming element).
Space and Time Complexity
Time Complexity: O(n * 50) ≈ O(n) because for each window we iterate over a constant range (50).
Space Complexity: O(1) since the extra space used (frequency array of fixed size 50) does not depend on n.
Solution
We use a sliding window approach combined with a frequency array for negative numbers. For each window:
- Update the frequency of negative numbers.
- To find the xth smallest negative value in the window, iterate from -50 to -1; subtract the count of each negative number from x until x becomes <= 0. The current number is the xth negative. If not found, the beauty is 0.
- Slide the window by removing the leftmost element (update frequency if negative) and adding the new incoming element (update frequency if negative).
This approach leverages the small range of negative numbers for an efficient solution.