Valid Subarrays With Exactly One Peak Problem
Description
LeetCode Problem 3874.
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 = 1 is a peak because nums[1] = 3 is greater than nums[0] = 1 and nums[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 i such that nums[i] is greater than both nums[i - 1] and nums[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 = 2 is a peak because nums[2] = 5 is greater than nums[1] = 3 and nums[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 <= 10^5-10^5 <= nums[i] <= 10^51 <= k <= n
Solution
Approach: Count per Peak
Collect all peak indices. A valid subarray contains exactly one peak p, so for each peak count the subarrays [l, r] with l <= p <= r, p - l <= k, r - p <= k and no other peak inside. The left end can go down to max(p - k, 0), but not past the previous peak, so at most to prevPeak + 1; likewise the right end goes up to min(p + k, n - 1) and stops before the next peak. The number of choices is the product of the two ranges, (p - leftMin + 1) * (rightMax - p + 1). Sum over all peaks.
Complexity: O(n) time and O(n) space.
class Solution:
def validSubarrays(self, nums: List[int], k: int) -> int:
n = len(nums)
peaks = []
for i in range(1, n - 1):
if nums[i] > nums[i - 1] and nums[i] > nums[i + 1]:
peaks.append(i)
ans = 0
for j, p in enumerate(peaks):
left_min = max(p - k, 0)
if j > 0:
left_min = max(left_min, peaks[j - 1] + 1)
right_max = min(p + k, n - 1)
if j < len(peaks) - 1:
right_max = min(right_max, peaks[j + 1] - 1)
ans += (p - left_min + 1) * (right_max - p + 1)
return ans