3874. Valid Subarrays With Exactly One Peak π
Description
You are given an integer array nums of length n and an integer k.
An index i is a peak if:
0 < i < n - 1nums[i] > nums[i - 1]andnums[i] > nums[i + 1]
A subarray [l, r] is valid if:
- It contains exactly one peak at index
ifromnums i - l <= kandr - i <= k
Return an integer denoting the number of valid subarrays in nums.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,3,2], k = 1
Output: 4
Explanation:
- Index
i = 1is a peak becausenums[1] = 3is greater thannums[0] = 1andnums[2] = 2. - Any valid subarray must include index 1, and the distance from the peak to both ends of the subarray must not exceed
k = 1. - The valid subarrays are
[3],[1, 3],[3, 2], and[1, 3, 2], so the answer is 4.
Example 2:
Input: nums = [7,8,9], k = 2
Output: 0
Explanation:
- There is no index
isuch thatnums[i]is greater than bothnums[i - 1]andnums[i + 1]. - Therefore, the array contains no peak. Thus, the number of valid subarrays is 0.
Example 3:
Input: nums = [4,3,5,1], k = 2
Output: 6
Explanation:
- Index
i = 2is a peak becausenums[2] = 5is greater thannums[1] = 3andnums[3] = 1. - Any valid subarray must contain this peak, and the distance from the peak to both ends of the subarray must not exceed
k = 2. - The valid subarrays are
[5],[3, 5],[5, 1],[3, 5, 1],[4, 3, 5], and[4, 3, 5, 1], so the answer is 6.
Constraints:
1 <= n == nums.length <= 105-105 <= nums[i] <= 1051 <= k <= n
Solutions
Solution 1: Simulation
Thinking
A valid subarray contains exactly one peak, and that peak lies within \(k\) of both ends. \(n \le 10^5\) forbids enumerating intervals.
Peaks separate one another. For a unique peak \(p\), the left end cannot reach the previous peak, the right end cannot reach the next, and both stay inside \([p-k,p+k]\).
Collect all peaks, then for each peak multiply the number of legal left ends by the number of legal right ends.
Neighboring-peak clamps enforce uniqueness.
We first traverse the array to find all peak positions and store them in a list \(\textit{peaks}\).
For each peak position, we calculate the left and right boundaries centered at the peak with a distance not exceeding \(k\). Note that if there are multiple peaks, we need to ensure the calculated subarray does not contain other peaks. Then, based on the left and right boundaries, we calculate the number of valid subarrays centered at each peak and accumulate it into the answer.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the length of the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |