We need to count subarrays that have a peak element. A peak is an element that is greater than its neighbors (both left and right neighbors within the subarray). The subarray must contain at least one peak? But careful: The definition: "subarrays that have a 'peak' element." So a subarray is considered to have a peak if there exists an index i within that subarray such that the element at i is greater than its immediate neighbors within the subarray. But note: The neighbors considered are the adjacent elements in the subarray. So if the peak is at the first or last position of the subarray, it only has one neighbor? Typically a peak is defined as an element greater than both its neighbors; but if the element is at the boundary of the subarray, it has only one neighbor within the subarray, so it cannot be a peak because it lacks two neighbors. Usually a peak is defined for interior elements only. So the subarray must contain at least one index i that is not at the boundaries of the subarray and such that the element is greater than both its adjacent elements (i.e., the left neighbor and right neighbor in the original array? Actually within the subarray). But careful: The subarray's neighbors are the elements directly adjacent to it within the subarray. If the subarray includes a peak from the original array but when placed in the subarray the peak's neighbors might be different? Actually if we take a subarray, we consider the relative positions. For an element at position i in the original array to be a peak within a subarray, we need that within that subarray, the element's left neighbor (if exists) and right neighbor (if exists) are both less than it. But for it to be a peak, it must have both neighbors within the subarray, because a peak needs to be greater than both neighbors. If the element is at the leftmost of the subarray, it has no left neighbor, so it cannot be a peak. Similarly for rightmost. So the element must be interior in the subarray. That means for an element at index i in the original array to be a peak in a subarray that includes it as an interior element, the subarray must extend at least one element to the left and one to the right of i. So the subarray's left bound L <= i-1 and right bound R >= i+1.
Thus we need to count the number of subarrays (contiguous) of the given array such that there exists at least one index i (with L < i < R) where nums[i] > nums[i-1] and nums[i] > nums[i+1] (considering the full array indices). However, note: The neighbors in the subarray are the immediate left and right elements within the subarray, which correspond to the immediate indices in the original array? Since subarray is contiguous, the left neighbor of i in the subarray is i-1 only if i-1 is included in the subarray; similarly right neighbor is i+1 only if i+1 is included. But for i to be interior, we need i-1 and i+1 to be within the subarray. So yes, the neighbors are exactly the adjacent indices in the original array. So the condition is exactly that i is a "peak" in the original sense (ignoring boundaries). However, careful: What about the values? The condition is nums[i] > nums[i-1] and nums[i] > nums[i+1]. That's it, regardless of the rest of the subarray. So any subarray that contains an index i where i is interior (i.e., not at the edges of the subarray) and nums[i] is a peak relative to its immediate neighbors will have that peak. But it's possible that a subarray contains multiple peaks; we count each subarray once if it has at least one peak.
We need to compute the total number of subarrays that contain at least one "peak" (interior element that is strictly greater than both its immediate neighbors in the original array). But wait: Could there be a subarray where an element that is not a peak in the original array becomes a peak within the subarray because the subarray excludes one of the neighbors? Example: nums = [1,2,3]. In the original, there is no peak because 2 is not greater than both 1 and 3; 3 is boundary; 1 boundary. Consider subarray [1,2,3] (full). 2 is interior but is less than 3, so not peak. But consider subarray [2,3]? Here interior? length 2 has no interior. So no. Consider [1,2]? No interior. So no. So in this case no peak subarray? But what about subarray [2]? length 1 has no interior. So none. That seems fine.
What about nums = [3,2,1]? No interior peaks because 2 is less than 3? Actually 2 is interior of full array: 3 > 2? Check: 2 is not greater than 3, so not peak. So none.
What about nums = [2,1,2]? At index 1 (value 1) is not peak; index 0 and 2 are boundaries. So no peaks in original. But consider subarray [2,1,2] (full): interior index 1 is 1, not peak. So none.
But consider nums = [1,3,2,4,1]. Peaks in original: index 1 (3>1 and >2), index 3 (4>2 and >1). Those are peaks. Subarrays that contain at least one of these peaks as interior. However, maybe there is a subarray where a non-peak element becomes a peak because one of its neighbors is missing? For an element to be interior, it must have both neighbors in subarray. So if we take an element that is not a peak in the original because it is only greater than one neighbor but not the other, but if the subarray excludes the neighbor that is greater? Wait, to be a peak, it must be greater than both neighbors within the subarray. So if we have an element at index i that originally has neighbors a and b. If a < nums[i] and b > nums[i], then nums[i] is not a peak because it is not > b. But if we take a subarray that excludes b (i.e., ends at i or doesn't include i+1), then i becomes the rightmost element; it cannot be interior because it lacks right neighbor, so it cannot be peak. Similarly if we exclude a, then i is leftmost. So i cannot become a peak by excluding one neighbor because then it's not interior. So the only way an element can be a peak in a subarray is if it is a peak in the original array and both its immediate neighbors are included in the subarray. However, wait: Could the neighbors within the subarray be different from the immediate neighbors in the original array? For a contiguous subarray, the neighbors of a given index i within the subarray are the elements at i-1 and i+1, provided they are in the subarray. That is exactly the same as original neighbors. So the only possibility for an element to be a peak in a subarray is that it is a peak in the original array. Because the values at i-1 and i+1 are fixed. So we can just focus on the set of indices i (1 <= i <= n-2) that are peaks in the original array. Then a subarray [L,R] (0-indexed inclusive) contains a peak if there exists a peak index p such that L < p < R. That is, the subarray includes p as an interior element. Note: We must have L <= p <= R? Actually interior: p must not be at L or R. So we need L <= p-1 and R >= p+1, equivalently L < p and R > p. So the subarray must include p and at least one element on each side.
Thus the problem reduces to: Count the number of subarrays of the array such that there is at least one peak index p with L < p < R. Equivalent to total subarrays minus subarrays that contain no peak as interior element. But careful: A subarray may include a peak index as a boundary? That doesn't count. So we need to exclude subarrays where either they have no peak index at all, or all peak indices within the subarray are at the boundaries? But if a peak index is at the boundary of the subarray, it is not interior, so it does not count as a peak. So the subarray fails. So we need subarrays that contain at least one peak index that is strictly inside the subarray. But note: if a subarray contains multiple peaks, it's counted once. So the count is the number of pairs (L,R) such that there exists a peak p with L < p < R. We can compute this directly.
Let n = length of nums. Total number of subarrays = n*(n+1)/2. But we need to subtract subarrays that have no interior peak. However, it might be easier to compute directly: For each peak p, count subarrays where p is a peak (i.e., where p is interior and the subarray contains p). But subarrays may contain multiple peaks; we must avoid double counting. So we can use inclusion-exclusion? That could be complicated.
Alternative approach: We can consider subarrays based on the leftmost peak they contain? Or we can compute the total number of subarrays that contain at least one peak interior by scanning and using intervals where there are no peaks? Actually we can consider the complement: subarrays that have no interior peak. What are these subarrays? They are subarrays where no peak index appears as an interior element. That means that for every peak index p, either p is not in the subarray, or if it is, it is at one of the boundaries (L or R). However, it's easier to characterize subarrays that have no interior peak: In such a subarray, all peak indices (if any) are at the boundaries only, or there are none. But more structure: For a subarray to have no interior peak, it means that the subarray cannot include any peak index with at least one element on both sides. That is, the subarray cannot fully "cover" a peak from both sides. But if a peak index p is included but at the left boundary (L = p) then it's not interior; similarly if R = p. So subarrays with no interior peak are those where the set of indices that are peaks intersect the interior of the subarray is empty. So the interior = indices from L+1 to R-1 contain no peak. So essentially, we need to count subarrays such that the interval (L+1, R-1) (i.e., the interior) contains no peak. That is, all peaks in the subarray must be at the endpoints (if any). So we need to count subarrays where the open interval (L,R) (i.e., excluding endpoints) contains no peak. Because interior indices are those strictly between L and R. So condition: For all i with L < i < R, i is not a peak. So we need to count subarrays (L,R) (0 <= L <= R < n) such that there is no peak index in (L,R). Also note: subarrays of length 1 (L=R) have no interior obviously, so they qualify as no interior peak. Similarly subarrays of length 2 (R=L+1) have no interior (since interior requires i such that L < i < R, i integer, but for length 2, L+1=R, no integer strictly between). So length 1 and 2 subarrays always have no interior peak. So those are included in the no-interior-peak set. So total subarrays without interior peak = number of subarrays where the open interval (L,R) contains no peak. Let's denote peaks as positions in a set P = {i | 1 <= i <= n-2 and nums[i] > nums[i-1] and nums[i] > nums[i+1]}. Then we need to count pairs (L,R) with L <= R such that (L,R) ∩ P = ∅. Because (L,R) means all integers strictly between L and R. If L >= R-1, then (L,R) empty, condition holds.
So we can count those subarrays by considering the gaps between peaks. Actually, the condition is that there is no peak in the interior. That means the subarray is either entirely within a region that has no peaks, but it can also stretch across peaks if it includes a peak as endpoint? Wait: If there is a peak at position p, and we take a subarray that includes p as interior? That's not allowed. But if we include p as an endpoint, it's okay. So subarrays that cross over a peak can be allowed if the peak is at L or R. For example, suppose we have a peak at p. Consider subarray [L,R] with L = p and R > p, then interior is (p,R) which does not include p, so it's okay if there is no other peak inside. Similarly [L,R] with R = p and L < p. Also subarrays that have both L and R on the same side of a peak, i.e., not covering the peak, or covering it at endpoint.
Thus the set of subarrays with no interior peak can be counted by splitting the array at peaks? But careful: The peaks are positions. We can think of the array as points 0,...,n-1. We need to count intervals [L,R] such that no peak lies strictly inside. This is like counting intervals that avoid a set of points, but they may include them as endpoints. In combinatorics, given a set of forbidden points that cannot be in the interior, we can count intervals that do not contain any forbidden point in the open interval. Equivalent to intervals where all points in the open interval are non-peak positions. This is similar to counting intervals in a line with some "bad" points that cannot be in the interior. This can be done by considering the maximal segments of consecutive non-peak positions, but also allowing intervals that span across peaks only if the peak is exactly at the endpoint.
A typical method: For each L, we can find the smallest R such that (L,R) contains a peak? Actually, for a fixed L, the subarrays with no interior peak are those R such that there is no peak p with L < p < R. That means R can go up to the first peak to the right of L, but not including it as interior. Let's define nextPeakAfterL = the smallest peak index > L. Then for R, we can have R in the range [L, nextPeakAfterL] inclusive? Check: If R = nextPeakAfterL, then interior (L,R) = (L, nextPeakAfterL). Since nextPeakAfterL is not included (as R is endpoint), interior does not contain that peak because it's at R. So it's okay. If R < nextPeakAfterL, obviously no peak. So R can be any index from L to nextPeakAfterL inclusive? But what about R > nextPeakAfterL? Then interior would include that peak because nextPeakAfterL < R and > L, so not allowed. So the allowed R for a given L are L <= R <= firstPeakRight(L), where firstPeakRight(L) is the smallest peak index greater than L; if no such peak exists, then R can be up to n-1. But careful: What if there is a peak at L itself? That is okay because it's at left endpoint. But if L itself is a peak, that's fine; the condition only cares about interior (L,R). So L can be a peak; that does not affect the allowed R as long as we don't have interior peaks. Similarly R can be a peak. So for each L, the maximum allowed R is the smallest peak index > L (call it p) OR n-1 if none. Actually, we must ensure that for any peak p' > L, if p' < R, then it's interior. So we must have R <= firstPeakRight(L). But if firstPeakRight(L) = L+? It's fine. So the count for L: number of valid R = (firstPeakRight(L) - L + 1) if firstPeakRight(L) exists, else (n - L). But also we must consider that if there is a peak at L? It doesn't matter. So this seems to work: For each L, the maximum R is the first peak to the right of L (including possibly that peak as endpoint). So valid R are L, L+1, ..., firstPeakRight(L). That yields count = firstPeakRight(L) - L + 1 (if such peak exists), else n - L.
But wait: Is that correct? Let's test with a small example. Consider array indices 0,1,2,3,4. Suppose peaks at positions 2 only. Then P = {2}. For L=0: first peak >0 is at 2. So valid R are R=0,1,2? R=2: interior (0,2) = {1}, no peak (2 is endpoint), ok. R=3? interior (0,3) includes 2? 2 is between 0 and 3, so interior contains peak 2 => not allowed. So max R=2. So count=3. Let's enumerate subarrays starting at L=0: [0,0], [0,1], [0,2] are ok. [0,3] and [0,4] not ok. So count 3, matches.
L=1: first peak >1 is at 2. So valid R = 1,2? R=1 (len1), R=2 (interior (1,2) empty, ok). R=3? interior (1,3) includes 2 => not ok. So count=2. Indeed: [1,1], [1,2] ok. [1,3] not.
L=2: first peak >2? none. So valid R up to n-1=4. So count = n-2 = 3? Actually n-L = 5-2=3, so R=2,3,4. But check: subarrays starting at 2: [2,2] ok (no interior). [2,3]: interior (2,3) empty? Actually interior is indices strictly between 2 and 3, which is none, so ok. [2,4]: interior (2,4) = {3}. 3 is not peak (peak is at 2, but 2 is endpoint). So ok. So count 3 correct.
L=3: first peak >3? none. So count = n-3=2: R=3,4. Check: [3,3],[3,4] ok. L=4: count=1. So total no-interior-peak subarrays = 3+2+3+2+1 = 11. Total subarrays n*(n+1)/2 = 5*6/2=15. So subarrays with interior peak = 15-11 = 4. Let's list all subarrays that have interior peak: Any subarray that includes 2 as interior, i.e., L < 2 < R. That means L in {0,1} and R in {3,4} with L <=1 and R >=3? Actually condition: L<2<R. So possible L: 0,1; R: 3,4; but also L=0,R=3; L=0,R=4; L=1,R=3; L=1,R=4. That's 4. Also what about L=0,R=2? No, interior empty. L=2,R=4? no. So 4 subarrays. That matches subtraction. So the simple per-L count seems to work.
But we must be careful: The condition we used: R <= firstPeakRight(L). That works if there is only one peak? But what if there are multiple peaks? For L, the first peak to the right of L is p1. Then any R > p1 would include p1 in interior because p1 is between L and R (since p1 > L). So not allowed. So indeed the maximum R is p1 (if p1 exists). So the count for L is exactly the distance to the next peak to the right (including the peak as endpoint) plus 1? Actually count = p1 - L + 1. But what about peaks that are at L? That doesn't matter. But what about the case where there is a peak at p1, but also another peak at p2 > p1. Since if R > p1, interior includes p1, so invalid. So indeed R must be <= p1. So the presence of further peaks doesn't matter; they are beyond p1, but if you try to extend beyond p1, you already invalid because p1 becomes interior. So for each L, the allowed R are up to the first peak after L. That's correct.
But wait: What about the scenario where there is a peak at position p and we consider L that is after p? Then firstPeakRight(L) would be the next peak after L, not the previous. So it's fine. So counting no-interior-peak subarrays as sum over L of (nextPeak(L) - L + 1) where nextPeak(L) = first peak index > L, or n if none. But careful: if there is no peak after L, then max R = n-1. So count = (n-1 - L + 1) = n - L. That matches.
But is this counting exactly subarrays with no interior peaks? Let's test with two peaks. Example: n=6, indices 0..5, peaks at 2 and 4. P={2,4}. Let's compute via sum:
For each L, nextPeak(L) = first peak > L.
- L=0: nextPeak=2 -> count = 2-0+1=3 (R=0,1,2)
- L=1: nextPeak=2 -> count = 2-1+1=2 (R=1,2)
- L=2: nextPeak=4? Wait: first peak >2 is at 4. So count = 4-2+1=3 (R=2,3,4)
- L=3: nextPeak=4 -> count = 4-3+1=2 (R=3,4)
- L=4: nextPeak=? >4 none? Actually maybe a peak at 4? 4 is a peak, but we need > L. L=4, first peak >4? none. So count = n-4=2 (R=4,5)
- L=5: count = 1.
Total = 3+2+3+2+2+1=13. Total subarrays = 21. So subarrays with interior peak = 8. Let's enumerate manually: Subarrays that have at least one interior peak. Interior peak means an index p such that L < p < R and p is a peak. The peaks are at 2 and 4.
Subarrays containing p=2 as interior: L <=1, R>=3. L can be 0 or 1; R can be 3,4,5? But careful: if R=4 or 5, we need to check if interior includes peak at 4? Actually if R>=5, interior (L,R) includes both 2 and 4. That's fine, still has interior peak. So for p=2 as interior: L in {0,1}, R in {3,4,5}. That's 23=6 subarrays. But some of those also contain peak 4 as interior; that's okay, we'll count union. Similarly subarrays containing p=4 as interior: L in {0,1,2,3}? Actually L <4, so L can be 0,1,2,3; R>4 => R can be 5. So L from 0..3 (4 choices), R=5 only? Also R could be >4? n=6, so max R=5. So R must be >=5? Actually R>4 => R=5. So count = 41 =4 subarrays: (0,5),(1,5),(2,5),(3,5). But note some of these already counted in the 6 from p=2: which ones? Those with L=0,1 and R=5: (0,5),(1,5) are in both. Also (2,5) and (3,5) are not in p=2's set because L must be <=1 for p=2 interior; L=2 is not <2? L=2 => L=2, then interior (2,?) would not include 2 because L=2, 2 is not > L, so p=2 is not interior if L=2. So those are distinct. So total distinct subarrays with interior peak = 6 + 4 - overlap? Overlap: subarrays that contain both peaks as interior. Which subarrays have both 2 and 4 interior? Need L <2 and R>4. L in {0,1}, R=5 only? Actually R>4 => R=5. So (0,5) and (1,5) are the ones. So overlap = 2. So total = 6+4-2=8. That matches our computed 8. Good.
Now compute via formula: total subarrays 21, no interior peak 13, difference 8. So the counting of no interior peak subarrays using nextPeak seems to work.
But need to verify the reasoning: For each L, we count R from L to nextPeak(L) inclusive. But is it always safe that if we take R up to nextPeak(L), the interior (L,R) contains no peak? Because the interior is (L,R). If R = nextPeak(L), then the only peak that could be in (L,R) is if there is a peak p with L < p < nextPeak(L). But nextPeak(L) is defined as the smallest peak > L. So there is no peak in (L, nextPeak(L)) by definition. So condition holds. For any R less than that, also holds. So indeed all those R are valid. And any R > nextPeak(L) would include that peak as interior, so invalid. So the count is correct.
But there is a nuance: What if L itself is a peak? That does not affect the nextPeak(L) because we look for peak > L, not >=. So it's fine. Also what about R being a peak? It's allowed as endpoint. So the nextPeak(L) might be a peak that becomes R, which is allowed.
Thus the number of subarrays with no interior peak = sum_{L=0}^{n-1} (nextPeak(L) - L + 1), where nextPeak(L) = min{ p in P | p > L } if exists, else n (i.e., treat as n, then count = n - L). Actually if we set nextPeak(L) to n when none, then term becomes n - L. That's consistent because we have n positions: R index up to n-1. So we need to compute nextPeak for each L efficiently.
We can precompute an array nextPeakPos[L] for L from 0 to n-1. This is essentially the next occurrence of a peak to the right. We can compute by scanning from right to left, storing the index of the next peak. Or we can just have a sorted list of peak positions. Since peaks are at most n, we can compute all peaks first, store them in a list, then for each L we can binary search for the smallest peak > L. That would be O(n log n). But we can also compute nextPeak in O(n) by scanning from right: If we know nextPeak[i] = if i+1 is peak? Actually we need for each L, the next peak strictly greater. We can compute an array nextPeakIdx of length n, initially set to n (meaning none). Iterate from rightmost to leftmost: if i is a peak, then nextPeakIdx[i] = i; else nextPeakIdx[i] = nextPeakIdx[i+1] (if i+1 < n). But careful: We need the next peak after L, not including L. So we want nextPeakAfter[L] = if i+1? Actually we can compute an array nextPeakPos[L] = smallest peak index > L. We can compute by scanning from right and keeping track of the next peak seen so far. Pseudocode:
Initialize next = n (or sentinel indicating none).
For i from n-1 down to 0:
if i is a peak: then next = i (since i is a peak, but for L = i-1 we want next = i? Wait, we want for each L, the next peak > L. So if we are at index i, we can store something for L = i-1? Better to compute an array nextPeakAfter[L] by after processing i+1? Simpler: We'll create an array nextPeakAfter of size n, initially n. Then we iterate i from n-2 down to 0? Let's think: For L = n-1, nextPeakAfter[n-1] = n (none). Then for i from n-2 down to 0: if i+1 is a peak? Actually we want to know the next peak after L, i.e., the smallest peak index > L. So if we maintain a variable nextPeak that holds the smallest peak index seen so far to the right, as we go leftwards, we can set nextPeakAfter[i] = nextPeak (since nextPeak is the smallest peak index > i? Let's do: start with nextPeak = n (none). For i from n-1 down to 0:
nextPeakAfter[i] = nextPeak; // because for L=i, nextPeakAfter[i] is the smallest peak > i (since we haven't yet considered if i is peak; we want > i)
if i is a peak: then set nextPeak = i; // now for indices left of i, the next peak becomes i.
Check: For i=n-1, nextPeakAfter[n-1] = n (since nextPeak initially n). If n-1 is a peak, then nextPeak becomes n-1. But for L = n-1, we want next peak > n-1, which is none, so n correct. For L = n-2, nextPeakAfter[n-2] = current nextPeak (which after processing n-1 is maybe n-1 if n-1 is a peak, else n). That's correct: the smallest peak > n-2 is either n-1 if it's peak, else none. Then if n-2 itself is a peak, we set nextPeak = n-2, but that will affect L=n-3. That seems correct: For L=n-3, nextPeakAfter[n-3] = nextPeak which after processing n-2 includes n-2 if peak, else maybe n-1 if peak etc.
But careful: In the iteration, we set nextPeakAfter[i] before updating if i is a peak. So for i that is a peak, nextPeakAfter[i] will be the next peak to the right, not including i. That's exactly what we want: nextPeakAfter[L] = smallest peak > L. So for a peak at i, nextPeakAfter[i] will be the next peak to the right, not i itself. So if we then later sum terms for L=i, the term uses nextPeakAfter[i] which is > i. But we want for L=i, the next peak after i (strictly greater). That is correct. And for L values that are not peaks, it's also correct. So this algorithm works: O(n) time.
But we must ensure that we compute peaks correctly: peak i if i>0 and i<n-1 and nums[i] > nums[i-1] and nums[i] > nums[i+1]. So we need to precompute a boolean array isPeak of length n, with isPeak[i] true for interior peaks.
Then compute nextPeakAfter as described:
int n = nums.length;
boolean[] isPeak = new boolean[n];
for (int i=1; i<n-1; i++) {
if (nums[i] > nums[i-1] && nums[i] > nums[i+1]) isPeak[i] = true;
}
int[] nextPeakAfter = new int[n];
int next = n; // sentinel for no peak
for (int i=n-1; i>=0; i--) {
nextPeakAfter[i] = next;
if (isPeak[i]) {
next = i;
}
}
Now the number of subarrays with no interior peak = sum_{L=0}^{n-1} (nextPeakAfter[L] - L + 1) if nextPeakAfter[L] < n? Actually if nextPeakAfter[L] == n, we want count = n - L (since R can be L..n-1). In our formula, if we treat nextPeakAfter[L] as n (which is beyond index n-1), then count = (n - L + 1)? That would be off by one. Let's check: We set nextPeakAfter[L] to n when no peak after L. But we need the maximum R is n-1. So we want count = (maxR - L + 1). maxR = n-1. So count = (n-1 - L + 1) = n - L. So if nextPeakAfter[L] = n, we should treat count = n - L, not n - L + 1. So the formula (nextPeakAfter[L] - L + 1) only works if nextPeakAfter[L] is a valid index (peak position) because maxR = nextPeakAfter[L] (the peak index itself). So we need conditional: if nextPeakAfter[L] == n, then count = n - L; else count = nextPeakAfter[L] - L + 1. But careful: What if nextPeakAfter[L] is a valid index, say p, then maxR = p (since p can be included as endpoint). So R from L to p inclusive gives count = p - L + 1. That matches. So we can implement accordingly.
Thus totalNoPeak = sum_{L=0}^{n-1} (nextPeakAfter[L] == n ? n - L : nextPeakAfter[L] - L + 1).
Then totalSubarrays = n*(n+1)/2. Answer = totalSubarrays - totalNoPeak.
But is this always correct? Let's test with edge cases: n=1. There are no peaks (since need at least three elements to have an interior). isPeak array all false. nextPeakAfter[0] = n=1? Our algorithm: next=1 initially, i=0, nextPeakAfter[0]=1, then isPeak[0]? false, so next remains 1. So nextPeakAfter[0]=1 => count = n - 0 = 1? Since nextPeakAfter[0]==1 which equals n? Actually n=1, so nextPeakAfter[0]==1 (n). So count = n - 0 =1. TotalNoPeak=1. totalSub=1*2/2=1. Answer=0. That is correct: no subarray has interior peak (since length less than 3 can't have interior). Good.
n=2: isPeak none. nextPeakAfter[0]=? next initialized n=2. i=1: nextPeakAfter[1]=2, isPeak[1]? false, next stays2. i=0: nextPeakAfter[0]=2. So for L=0: count = n - 0 =2? Actually n=2, so count = 2-0=2? But R from 0 to 1: that's 2 subarrays: [0,0] and [0,1]. Yes that's 2. L=1: count = n-1 =1? Actually nextPeakAfter[1]=2==n, so count = n-1 =1. That gives [1,1]. So totalNoPeak=3. totalSub=3. Answer=0. Good.
n=3 with no peaks: example [1,2,3] no peaks. Compute peaks: isPeak[1]? 2>1 and 2>3? 2>3 false, so false. So no peaks. nextPeakAfter for all L = n=3. Then counts: L=0: 3-0=3 (subarrays starting at 0: R=0,1,2). L=1: 3-1=2 (R=1,2). L=2: 3-2=1 (R=2). totalNoPeak=6, totalSub=6, answer=0. Indeed there is no interior peak because length 3 has only index 1 as interior but it's not peak.
n=3 with a peak at index 1: example [3,1,3]? Wait 1 is not > both neighbors. Peak at 1 requires > both. Let's pick [2,5,1]. 5>2 and 5>1 => peak at 1. So isPeak[1]=true. Then compute nextPeakAfter: start next=3. i=2: nextPeakAfter[2]=3, isPeak[2] false => next=3. i=1: nextPeakAfter[1]=3, isPeak[1] true => set next=1. i=0: nextPeakAfter[0]=1 (since next now 1). So for L=0: nextPeakAfter[0]=1 (not n), count = 1-0+1=2 => R=0,1. But R=1: interior (0,1) empty, ok. L=1: nextPeakAfter[1]=3 (==n?) n=3, so next=3 => count = n-1 = 2? Actually n=3, L=1 => count = 3-1=2? That gives R=1 and R=2? But R=2: interior (1,2) is empty? Actually (1,2) has no integer? Since 1< i <2 none. So it's allowed. That matches. L=2: nextPeakAfter[2]=3 => count = n-2=1. So totalNoPeak = 2+2+1=5. totalSub=6. answer=1. Which subarray has interior peak? Must have L<1<R => L=0 and R=2. That's [0,2] only. So answer=1, correct.
So algorithm seems solid.
Now complexity: O(n) time, O(n) space. Could be done in O(1) extra? Possibly but we need to compute peaks and nextPeak. But O(n) is fine.
But wait: Our counting of no-interior-peak subarrays using nextPeakAfter might overcount subarrays that include a peak at an endpoint but also have another peak interior? No, because if there is another peak interior, then that interior peak would be > L and < R, and since we are only allowing R up to the first peak after L, we guarantee that there is no peak in (L,R). But what if there is a peak before L? That doesn't matter because interior only considers >L. So the condition is exactly that the interval (L,R) is free of peaks. So the first peak after L is the limiting factor. So the sum method is correct.
Thus answer = totalSubarrays - sum_{L} ( (nextPeak(L) == n ? n - L : nextPeak(L) - L + 1) ).
We can compute directly.
Let's test with a more complex example: nums = [1,2,3,2,1,2,3,2,1] (like a zigzag). Let's find peaks: indices: 2 (3>2 and >2), 6 (3>2 and >2). So peaks at 2 and 6. n=9. Let's compute manually maybe.
But our algorithm should work.
Edge Cases: If there are many peaks, nextPeakAfter for each L is the immediate next peak. So we need to compute nextPeakAfter properly.
Potential pitfalls: The nextPeakAfter array defined as above yields the smallest peak index > i. That is correct. But note: For L = i, we use nextPeakAfter[L] as the first peak strictly greater than L. That's fine.
But is there any subarray that has no interior peak but whose interior includes a peak that is not the first after L? No, because if there is any peak in interior, the first one after L is definitely in interior (since it's > L and <= the peak). So if interior contains any peak, then firstPeakAfter(L) would be <= interior's smallest peak, and thus < R, so R > firstPeak. So our condition R <= firstPeakAfter(L) ensures interior empty. So it's necessary and sufficient.
Thus the complement counting is correct.
So we can implement function countPeakSubarrays(nums) returning number of subarrays that have a peak.
But note: The problem statement says "subarrays that have a 'peak' element." It doesn't specify that the peak must be interior in the subarray? Typically a peak is defined relative to its immediate neighbors. If we have subarray of length 1, there is no neighbor, so can't be peak. Length 2: each element has only one neighbor, so not greater than both. So indeed only subarrays of length >=3 can have a peak, and within that, the peak must be at an index that is not at the ends of the subarray. That matches our interpretation.
But we should double-check if the problem intends something else: Could it be that a peak is defined as an element greater than its neighbors in the original array, not subarray? The description: "A peak is an element greater than its neighbors." Usually in problems, when you have a subarray, you consider the elements within the subarray and the neighbors within that subarray. So it's relative to the subarray. That is what we used. So it's fine.
One nuance: If the subarray includes a peak from the original but if we slide the subarray, the neighbors of that element within the subarray are the ones adjacent in the subarray, which are the same as original if the subarray is contiguous and includes both immediate neighbors. So it's consistent.
Thus algorithm: Compute peaks in original. Compute nextPeakAfter array. Sum over L the count of valid R without interior peaks. Subtract from total subarrays.
Let's derive formula more elegantly: total = n*(n+1)/2. totalNoPeak = sum_{L=0}^{n-1} ( min( nextPeakAfter[L], n-1 ) - L + 1 )? Actually if nextPeakAfter[L]==n, we want maxR = n-1. So we can treat nextPeakAfter[L] = min( nextPeakAfter[L], n-1 )? But careful: If nextPeakAfter[L] is a valid peak index p (<= n-2 maybe), we want maxR = p, not n-1. So we can compute maxR = (nextPeakAfter[L] == n) ? n-1 : nextPeakAfter[L]; and count = maxR - L + 1. That works.
Implementation: we can compute totalNoPeak = 0; for L from 0 to n-1: if nextPeakAfter[L] == n: totalNoPeak += (n - L); else totalNoPeak += (nextPeakAfter[L] - L + 1);
Alternatively, we can compute directly totalWithPeak = total - totalNoPeak.
Now check: In the sum, if nextPeakAfter[L] = p, count includes subarrays where R = p. That's fine because p is endpoint. If p is a peak, that subarray's interior does not include p. But what if that subarray also includes another peak as interior? That can't happen because p is the first peak after L. If there is another peak q > p, then to have R = p, interior (L,p) does not include q. So safe. If we had R > p, that would be invalid because p becomes interior. So our allowed set is exactly those subarrays that have no interior peaks.
Thus answer = totalSub - totalNoPeak.
We need to write a function. Let's test with the earlier two-peak example: peaks at 2,4, n=6. Compute nextPeakAfter:
Initialize next=6.
i=5: nextPeakAfter[5]=6; isPeak[5]? false -> next stays6.
i=4: isPeak[4]? index 4 is >? Actually peaks at 4? Yes, we have peak at 4. So nextPeakAfter[4]=6 (since next currently 6); then set next=4.
i=3: nextPeakAfter[3]=4; isPeak[3]? false; next remains4.
i=2: isPeak[2]? true; nextPeakAfter[2]=4; then set next=2.
i=1: nextPeakAfter[1]=2; isPeak[1]? false.
i=0: nextPeakAfter[0]=2; isPeak[0]? false.
Thus nextPeakAfter: [2,2,4,4,6,6] (indices 0..5). But we need to check: For L=2, nextPeakAfter[2]=4, correct (first peak >2 is 4). For L=4, nextPeakAfter[4]=6 (none). So counts:
L=0: p=2 -> count=2-0+1=3
L=1: p=2 -> 2-1+1=2
L=2: p=4 -> 4-2+1=3
L=3: p=4 -> 4-3+1=2
L=4: p=6==n -> count = n-4 = 2? Actually n=6, so count = 6-4=2. But earlier we computed count=2 for L=4? Wait earlier we did n=6, L=4 gave count=2? Actually earlier we had L=4: count = 2 (R=4,5) which is n-4=2. Yes.
L=5: p=6 => count = n-5=1.
Sum=3+2+3+2+2+1=13. same.
So works.
Now, what about peaks at the very ends? Since peaks are only defined for interior indices (1..n-2), they never include index 0 or n-1. So nextPeakAfter[L] will always be > L and <= n-2? Actually could be up to n-2 if there is a peak at n-2. That's fine.
Now, check scenario where there is a peak at index 1? That's allowed because it's interior? Actually index 1 is interior if n>=3, yes because i=1 has neighbors at 0 and 2. So it's a peak. For L=0, nextPeakAfter[0] would be 1? But is that correct? Let's test: n=3, peaks at 1 (like [3,5,2]? Actually 5>3 and >2). Then isPeak[1]=true. Compute nextPeakAfter: next=3; i=2: nextPeakAfter[2]=3; i=1: nextPeakAfter[1]=3, set next=1; i=0: nextPeakAfter[0]=1. So for L=0, p=1, count = 1-0+1=2 => R=0,1. That includes subarray [0,1] length 2. That's allowed. And [0,2] is not allowed because that would include peak 1 as interior? Actually [0,2] has L=0,R=2, interior (0,2) includes 1, which is a peak, so not allowed. So correct. For L=1: p = nextPeakAfter[1] = 3 (none) => count = n-1 = 2? n=3, L=1 => count = 3-1=2, meaning R=1,2. Subarray [1,1] and [1,2]. [1,2] has no interior (since length2 interior empty). So okay. So totalNoPeak=2+2+1=5? Actually L=2: count = n-2=1. Sum=2+2+1=5. totalSub=6, answer=1. The only interior peak subarray is [0,2]. Correct.
Now consider a case where peaks are adjacent? For example, array: [1,3,2,4,1]. Peaks at index 1 (3) and index 3 (4). They are not adjacent; index difference 2. Adjacent peaks can't happen? Because if you have two adjacent indices i and i+1 both peaks, then we require nums[i] > nums[i-1] and > nums[i+1]; and nums[i+1] > nums[i] and > nums[i+2]. But if nums[i] > nums[i+1] and nums[i+1] > nums[i], contradiction. So two adjacent peaks can't happen because they would need to be greater than each other. So peaks must be at least 2 apart. So there is always at least one non-peak between peaks. That's fine.
Now is there any scenario where a subarray has interior peak but it's not captured by the simple condition that there is a peak p with L<p<R? No, that's exactly definition.
Thus answer is straightforward.
But we need to write a function. The function signature: maybe in Java? Or Python? The problem statement says "Write a function to find the number of subarrays that have a "peak" element." It doesn't specify language, but we can provide in Python or Java. Let's do Python for simplicity.
We'll define:
def count_peak_subarrays(nums: List[int]) -> int:
n = len(nums)
if n < 3:
return 0 # Actually there can be no subarray with interior peak because minimum length 3 required, but we can also compute via algorithm which yields 0.
# compute is_peak
is_peak = [False] * n
for i in range(1, n-1):
if nums[i] > nums[i-1] and nums[i] > nums[i+1]:
is_peak[i] = True
# compute next_peak_after
next_peak_after = [n] * n # default n means none
nxt = n
for i in range(n-1, -1, -1):
next_peak_after[i] = nxt
if is_peak[i]:
nxt = i
total_no_peak = 0
for L in range(n):
p = next_peak_after[L]
if p == n:
total_no_peak += (n - L)
else:
total_no_peak += (p - L + 1)
total_sub = n * (n+1) // 2
return total_sub - total_no_peak
Test with examples.
But need to be careful: The total_no_peak count includes subarrays that may have no interior peak because they have length 1 or 2, or longer but no interior peaks. Our subtraction gives those with at least one interior peak.
Let's test with earlier two-peak example: [1,3,2,4,1]? Actually that's peaks at 1 and 3. n=5. Compute: total_sub=15. Compute peaks: i=1:3>1 and >2 true; i=2:2 not >3 and >4? no; i=3:4>2 and >1 true. So peaks at 1,3. next_peak_after: i=4: nxt=5, next[4]=5, is_peak[4]? false. i=3: next[3]=5, is_peak[3]=true => nxt=3. i=2: next[2]=3, is_peak[2]=false. i=1: next[1]=3, is_peak[1]=true => nxt=1. i=0: next[0]=1, is_peak[0]=false. So next = [1,3,3,5,5]. Then L=0: p=1 => count=1-0+1=2; L=1: p=3 => 3-1+1=3; L=2: p=3 => 3-2+1=2; L=3: p=5=> n? p=5==n? n=5, yes, so count = n-3=2? Actually n=5, L=3 => count = 5-3=2? That's 2? But careful: if p=5 means none, count = n-L =5-3=2 => R=3,4. That's two. L=4: p=5 => count=5-4=1. total_no_peak=2+3+2+2+1=10. total_sub=15 => answer=5. Let's enumerate subarrays with interior peak: Need L<p<R for p=1 or p=3. For p=1: L<1<R => L=0, R>=2. R can be 2,3,4. That's 1*3=3 subarrays: [0,2],[0,3],[0,4]. For p=3: L<3<R => L can be 0,1,2; R must be 4 (since R>3 and max index 4). So L=0,1,2 with R=4 => 3 subarrays: [0,4],[1,4],[2,4]. Overlap: subarrays that have both peaks interior: need L<1 and R>3 => L=0, R=4 only. That's [0,4] counted twice. So total distinct = 3+3-1=5. Matches.
So algorithm works.
Now we should write explanation and code.
But we must also consider if the array has many peaks and we use O(n) time, that's fine.
However, there is an alternative approach: we could directly count subarrays with at least one interior peak by counting for each peak, the number of subarrays where it is the first interior peak? Or use inclusion-exclusion by subtracting those with none. The complement method we used seems simplest.
But let's double-check the complement method thoroughly: Is there any subarray that has no interior peak but our count includes it? We counted subarrays based on L and max R = nextPeakAfter[L]. This ensures that interior (L,R) contains no peak. But what about subarrays where L and R are such that there is a peak in interior but the first peak after L is not included because maybe we skip it? That's impossible: if there is any peak in interior, the smallest peak > L is definitely <= that interior peak, and if that smallest peak is < R, then it's interior. So R must be <= firstPeak to avoid interior peaks. So condition is necessary. Conversely, if there is no peak in (L,R), then the first peak after L must be >= R (or none). So R <= firstPeakAfter[L] holds. So our condition is exactly that (L,R) contains no peak. So the complement set is correctly counted.
One more nuance: What about subarrays where the interior contains a peak but that peak is not the first after L because there is a peak before L that is inside? That can't happen: peaks before L are not in (L,R). So fine.
Thus the solution is correct.
Now we need to provide the function and explanation.
We should also consider the possibility that the array may have repeated values. Peak definition uses strict greater than both neighbors. So if neighbors are equal, not peak.
Now let's consider complexity: O(n) time, O(n) space for isPeak and nextPeakAfter. Could we reduce space to O(1) by not storing arrays? Possibly by scanning and accumulating sum on the fly: We can compute peaks list and then for each L, the next peak after L can be found by scanning from L? That would be O(n^2). Better to precompute nextPeakAfter in O(n) with O(n) space. That's acceptable.
Alternatively, we can compute totalNoPeak by processing segments between peaks. Let's try to derive a formula based on distances between peaks.
Let P = sorted list of peak indices. Also we might consider the boundaries: Define p0 = -1, p_{m+1} = n (sentinel). But careful: our nextPeakAfter[L] is the first peak > L. So for L in the interval between consecutive peaks (including at a peak?), we can compute counts. For L in [p_i + 1, p_{i+1}]? Actually need to partition L from 0 to n-1. The first peak after L depends on which segment L falls into. For L <= first peak index p0, nextPeakAfter[L] = p0 for L < p0, and for L = p0? The next peak after p0 is p1 if exists else n. Because for L = p0, we want > L, so it's p1 (or n). But our algorithm gave for L = p0, nextPeakAfter[L] = p1 (if exists) because we set next after updating at i=p0. Let's check: For i=p0, we set nextPeakAfter[p0] = current next (which is p1 because we have not yet updated to p0? Wait scanning from right: Suppose peaks at p0, p1, ... We process descending. When i = p0, at that moment next = p1? Actually careful: We start with next = n. Then we iterate from n-1 down to 0. When we encounter the rightmost peak, say p_last, we set nextPeakAfter[p_last] = current next (which is maybe n or maybe a later peak? Since we are moving right to left, when we reach p_last, next currently is whatever was set after processing indices > p_last. Since there are no peaks > p_last, next is n originally, so nextPeakAfter[p_last] = n. Then we set next = p_last. Then for i = p_last-1 down to next peak (p_{last-1}), next = p_last. So for any L in (p_{last-1}, p_last) (i.e., less than p_last but greater than previous peak), nextPeakAfter[L] = p_last. When we reach i = p_{last-1}, nextPeakAfter[p_{last-1}] = next which is p_last, then we set next = p_{last-1}. So for L = p_{last-1}, nextPeakAfter[p_{last-1}] = p_last (the next peak after p_{last-1}). So indeed for L that is exactly a peak index, nextPeakAfter[L] is the next peak to the right, not including itself. So that matches definition. So the intervals: For L in [0, p0) (if p0 is first peak), next = p0; for L = p0, next = p1 (or n); for L in (p0, p1) (i.e., p0+1 to p1-1), next = p1; for L = p1, next = p2; etc. So we can compute sum by iterating over segments. But not needed.
Now we need to provide explanation. We'll explain the approach: complement counting, compute next peak after each position, sum counts.
But also we must note that subarray must have interior peak, which requires length at least 3.
Now, is there any possibility that a subarray contains a peak that is not a peak in the original array because the subarray edges cut off one of the neighbors? For example, consider nums = [5, 1, 5]. Original: index 1 is 1, not peak. But if we take subarray [0,1], no interior. [1,2] no interior. [0,2] interior index 1 is 1, not peak. So no. What about nums = [5, 10, 5, 10, 5]? Actually peaks at 1 and 3. But consider subarray [1,3] length 3: interior index 2? Wait indices: subarray [1,3] includes indices 1,2,3 of original? Actually original indices 1=10,2=5,3=10. The interior index is 2 (value 5) which is not a peak. But the subarray includes peaks at 1 and 3 but they are endpoints (L=1, R=3). So they don't count. So no interior peak. Our method: For L=1, nextPeakAfter[1] =? peaks at 1 and 3. nextPeakAfter[1] = next peak >1, which is 3. So maxR =3. So subarray [1,3] is allowed (R=3). So it's counted in no-interior-peak. That's correct. So the two peaks at endpoints don't contribute.
Thus correct.
Now consider a scenario where there is a peak at index i, and we take subarray that includes i as interior but also includes other peaks. That's fine.
Now think about correctness for large n.
Potential overflow: total_sub = n*(n+1)//2 may overflow 32-bit int in some languages, but Python int is fine. In Java use long.
Now we can write final answer.
But we must ensure that the problem statement might have different interpretation: Could a "peak" be defined as an element that is greater than its immediate neighbors in the original array regardless of subarray boundaries? That is, a peak in the original array is a position i such that nums[i] > nums[i-1] and nums[i] > nums[i+1]. Then a subarray "has a peak" if it contains at least one such peak index (anywhere within the subarray, not necessarily interior). But that would be weird because if the subarray includes the peak at its boundary, does that count? The phrase "has a 'peak' element" might mean the subarray contains an element that is a peak in the original array. But usually when we talk about peaks in subarray, we consider within the subarray. However, it's ambiguous. Let's examine typical problems: "Count subarrays with peak element" might refer to subarrays where there exists an element that is greater than its neighbors (within the subarray). That's what we used. I think it's correct. But we must check if the subarray includes the peak at the boundary, does that satisfy "peak element"? If the peak is at the first position of the subarray, in the subarray it has only right neighbor; is it considered a peak? Typically no, because a peak needs two neighbors. So the peak must be interior. So our interpretation is consistent.
I'll search my memory: There's a known LeetCode problem "Number of Subarrays with Peak Element"? Actually there is a problem "Count Number of Homogenous Substrings", etc. Not recall exactly. But this is a plausible problem.
Thus we'll provide solution accordingly.
Now we'll produce final answer: explanation and code.
We'll also include edge case: if n<3, answer=0 because no interior possible. But our algorithm also yields 0 because total_no_peak equals total_sub. Actually for n<3, total_sub: n=2 => 3, our computed nextPeakAfter will have no peaks, so total_no_peak = total_sub, answer=0. So we can just use general algorithm; no need special case.
But careful: For n=2, nextPeakAfter[0] = n? Since no peaks, next stays n. So count for L=0: n-0=2; L=1: n-1=1; total_no_peak=3, answer=0. Good. For n=1: L=0: count=n-0=1, total_sub=1, answer=0.
So we can skip explicit n<3 check.
Now time complexity O(n), space O(n). Could we reduce to O(1) space? Possibly by scanning and computing total_no_peak without storing nextPeakAfter for all L: we could iterate from right to left and maintain nextPeak, and also maintain the sum by grouping L's? Actually we can compute the sum by iterating L from n-1 down to 0 while updating nextPeak. But sum_{L} (nextPeakAfter[L] - L + 1) can be computed as we go: For each L from n-1 downwards, we know nextPeakAfter[L] = nextPeak (which is the next peak to the right). So we can incrementally add. So we could compute total_no_peak in a single pass without storing the whole array, just keeping current nextPeak. But we need to process L in increasing order? Actually we can compute sum in reverse: starting from L=n-1 down to 0, we know nextPeak after L (which we maintain as we go left). We can just accumulate: total_no_peak = 0; next = n; for i from n-1 to 0: total_no_peak += (next - i + 1) if next != n else (n - i). But careful: if next == n, we add (n - i). But we need to be careful: The formula for each L is: if next == n: add (n - L) else add (next - L + 1). So we can do that in the loop without storing nextPeakAfter. Then after adding, we check if current i is a peak; if yes, set next = i. That yields total_no_peak directly. So O(1) extra space (besides is_peak boolean array or we can compute peaks on the fly? We need to know isPeak[i] when we process i from right to left. But we can compute isPeak on the fly if we have the array? We need to compare nums[i] with nums[i-1] and nums[i+1]. For i we need nums[i-1] and nums[i+1]. If we are scanning from right to left, at index i we have access to nums[i], and also nums[i+1] is next (to the right) and nums[i-1] is left neighbor, but i-1 may not be processed yet? That's fine because we have the whole nums array. So we can compute isPeak[i] as we iterate, since we have nums. But we need to know i+1 and i-1. At the moment of processing i, i+1 is already processed? Not needed. We just need values: nums[i-1], nums[i], nums[i+1]. All are from the original array, we have them. So we can compute on the fly. However, note: For i=0 or i=n-1, they cannot be peaks. So we can skip. So we can avoid storing isPeak array entirely, just compute a condition. So we can achieve O(1) extra space (ignoring input and output). That's nice.
Let's design O(1) space algorithm:
Initialize total_no_peak = 0, next_peak = n (meaning none). Iterate i from n-1 down to 0:
if next_peak == n:
add = n - i
else:
add = next_peak - i + 1
total_no_peak += add
// then check if i is a peak (i between 1 and n-2)
if 1 <= i <= n-2 and nums[i] > nums[i-1] and nums[i] > nums[i+1]:
next_peak = i
After loop, total_sub = n*(n+1)//2, answer = total_sub - total_no_peak.
Test with earlier example n=5 peaks at 1,3. Let's simulate:
n=5, next_peak =5.
i=4: add = 5-4=1; total=1; isPeak? i=4 (n-1) not peak => next_peak stays5.
i=3: add = 5-3=2; total=3; check i=3 (peak? yes: >2 and >1? Actually nums[3]>nums[2] and >nums[4]? Let's assume the array values. We'll assume peaks at 1 and 3. So i=3 is peak, so next_peak=3.
i=2: add = next_peak - i + 1 = 3-2+1=2; total=5; i=2 not peak.
i=1: add = next_peak - i +1 = 3-1+1=3; total=8; i=1 is peak -> next_peak=1.
i=0: add = next_peak - 0 +1 = 1-0+1=2; total=10. Is i=0 peak? no.
total_no_peak=10. total_sub=15, answer=5. That matches earlier where total_no_peak=10? Wait earlier we computed total_no_peak=10? We computed 2+3+2+2+1=10 for that example? Actually earlier for peaks at 1 and 3 we had next array: L=0 count=2, L=1 count=3, L=2 count=2, L=3 count=2, L=4 count=1 => sum=10. Yes. So this matches.
Test with one peak at 1 (n=3): nums = [2,5,2]. n=3.
next_peak=3.
i=2: add = 3-2=1; total=1; i=2 not peak.
i=1: add = 3-1=2; total=3; i=1 is peak => next_peak=1.
i=0: add = next_peak - 0 +1 = 1-0+1=2; total=5. total_no_peak=5. total_sub=6 => answer=1. That matches earlier (we had total_no_peak=5? Actually earlier we computed total_no_peak=5? Let's recalc: For n=3 with peak at 1, we had L=0: p=1 -> count=2? Wait earlier we had L=0: p=1 -> count=1-0+1=2; L=1: next_peak= n (3) -> count = n-1=2; L=2: count = n-2=1; sum=5. Yes. So 5. Good.
Test with two peaks earlier: peaks at 2 and 4, n=6. Simulate:
next=6.
i=5: add=6-5=1; total=1; not peak.
i=4: add=6-4=2; total=3; i=4 peak => next=4.
i=3: add=4-3+1=2; total=5; not peak.
i=2: add=4-2+1=3; total=8; i=2 peak => next=2.
i=1: add=2-1+1=2; total=10; not peak.
i=0: add=2-0+1=3; total=13; not peak.
total_no_peak=13, total_sub=21, answer=8. Good.
Test with no peaks: all false. next remains n throughout. Then for i from n-1 down to 0: add = n - i, total = sum_{i=0}^{n-1} (n-i) = sum_{k=1}^{n} k = n(n+1)/2 = total_sub. So answer 0. Good.
Thus O(1) extra space algorithm works.
Now we must be careful: The addition (next_peak - i + 1) only valid when next_peak < n. But we can write: if next_peak == n: add = n - i else add = next_peak - i + 1. That's fine.
One more nuance: The logic of setting next_peak = i after processing i: Because for L values less than i, the next peak after L will be i if there is no other peak between L and i. That's correct. Since we process from right to left, when we encounter a peak at i, we update next_peak to i, which becomes the next peak for all indices left of i until we encounter another peak.
Thus we have a clean solution.
Now we need to write a function that returns the count. Provide explanation.
Let's craft final answer:
- Step 1: Identify indices i (1 <= i <= n-2) such that nums[i] > nums[i-1] and nums[i] > nums[i+1]; these are peaks.
- Step 2: Count subarrays with no interior peak. For a fixed left endpoint L, the right endpoint R can extend at most to the first peak index to the right of L (including it) because if we go beyond, that peak becomes interior. So number of valid R for given L = (firstPeakAfter(L) - L + 1) if firstPeakAfter(L) exists, else (n - L). (Where firstPeakAfter(L) is the smallest peak index > L.)
- Step 3: Sum this count over all L to get totalNoPeak.
- Step 4: Answer = total_subarrays - totalNoPeak.
We can compute firstPeakAfter(L) efficiently in one pass from right to left: maintain variable nextPeak, initially set to n (meaning none). For i from n-1 down to 0, the value of nextPeak is the smallest peak index > i. So we can directly add the count for L=i and then if i itself is a peak, update nextPeak=i.
Complexities: O(n) time, O(1) extra space (besides input).
Edge cases: n<3 => answer 0.
We'll provide code in Python.
Now we should produce final answer with code and explanation.
But before finalizing, we should test some random arrays to ensure no off-by-one.
Let's test n=4, peaks? Example: [1,3,2,4] peaks: index1:3>1 and >2 true; index2:2? 2<3 and <4 not; index3 boundary. So only peak at 1. n=4.
Compute manually: subarrays with interior peak: need L<1<R => L=0, R>=2. R can be 2 or 3? Actually R must be >1, so R=2 or 3. That gives [0,2] and [0,3]. Also L could be? L must be <1, only L=0. So two subarrays. Also check if there are subarrays with interior peak at index 1? That's it. Could there be subarray where peak at 1 is interior with L=0,R=2 and L=0,R=3. That's 2. Answer should be 2.
Now run algorithm:
n=4, next_peak=4.
i=3: add=4-3=1; total=1; i=3 not peak (boundary)
i=2: add=4-2=2; total=3; i=2? check: is peak? i=2, neighbors: nums[2]=2, left=3, right=4: 2>3? no. So not peak.
i=1: add=4-1=3; total=6; i=1 is peak => next_peak=1.
i=0: add = next_peak - 0 +1 = 1-0+1=2; total=8. total_no_peak=8. total_sub=4*5/2=10. answer=2. Good.
Another test: n=4 with peaks at 2? Let's try [5,1,5,1]? Actually index1:1 not peak; index2:5>1 and >1? neighbors: index1=1, index3=1 => 5>1 and >1 true. So peak at 2. n=4.
Compute manually: interior peak at 2 requires L<2<R => L in {0,1}, R must be >=3? Actually R>2 => R can be 3 only because n-1=3. So possible (0,3) and (1,3). That's 2 subarrays. Also if L=0,R=2? R=2 not >2, so not. So answer=2.
Algorithm:
next=4.
i=3: add=4-3=1; total=1; i=3 not peak (boundary)
i=2: add=4-2=2; total=3; i=2 peak => next=2.
i=1: add = next - 1 + 1 = 2-1+1=2; total=5; i=1 not peak.
i=0: add = next - 0 +1 = 2-0+1=3; total=8. total_no_peak=8. total_sub=10. answer=2. Good.
Test: n=5, peaks at 1 and 3? Already did.
Test: n=5, peaks at 2 only? Example [1,2,5,2,1]. Peak at index2 (5). Let's compute manually: interior peak at 2 => L<2<R => L can be 0,1; R can be 3,4. So 2*2=4 subarrays: (0,3),(0,4),(1,3),(1,4). Also could L=0,R=2? no; L=2,R=4? L not <2. So 4. Answer=4.
Algorithm:
n=5, next=5.
i=4: add=5-4=1; total=1; not peak.
i=3: add=5-3=2; total=3; not peak.
i=2: add=5-2=3; total=6; i=2 peak => next=2.
i=1: add = next -1+1 =2-1+1=2; total=8; not peak.
i=0: add = next -0+1 =2-0+1=3; total=11. total_no_peak=11. total_sub=15 => answer=4. Good.
Test: n=6, peaks at 2 and 4? Already.
Test: n=7, peaks at 2 and 5? Actually need at least 2 apart. Let's test random.
But seems correct.
Now we need to ensure that the code correctly handles n=0? But nums array is given, presumably non-empty. But we can handle empty: return 0.
Now produce final answer.
But wait: There is a subtlety: The definition of peak element: "greater than its neighbors." Could it be that the neighbors are considered in the original array, not the subarray? The phrase "has a 'peak' element" might be interpreted as: The subarray contains an element that is a peak in the original array (i.e., greater than its original neighbors). That is a simpler problem: just count subarrays that contain at least one index that is a peak in the original array (any position, not necessarily interior of subarray). But if the subarray includes that peak at its boundary, does that count? The peak definition in original array doesn't depend on subarray boundaries. So if a subarray includes a peak index at any position (including endpoints), it would "have a peak element". However, the problem statement: "A peak is an element greater than its neighbors." It doesn't say that the neighbors must be within the subarray; it's a property of the element in the original array. Usually a peak is defined for an array as a whole: an element that is greater than its immediate neighbors. So when we say a subarray has a peak element, it likely means there is an element in that subarray that is a peak in the original array. But we need to consider: if the peak is at the boundary of the original array, it would have only one neighbor, so it's not a peak (since needs both). So peaks are always interior in the original array. So any subarray that includes that index, regardless of whether the index is interior in the subarray, still the element is a peak (since its original neighbors are still there? Actually if the subarray cuts off one of its neighbors, does the element still qualify as a peak? The definition "greater than its neighbors" is independent of the subarray, it's about the original array. So even if the subarray does not include both original neighbors, the element itself in the original array is still a peak. The subarray "has a peak element" if it contains such an element. The fact that the subarray doesn't include one of the neighbors doesn't change that the element itself is a peak relative to its original neighbors. So the subarray wouldn't need to have the peak as interior; it just needs to contain the index. That seems plausible. Let's read the problem statement: "You are given an array of integers nums. Write a function to find the number of subarrays that have a 'peak' element. A peak is an element greater than its neighbors." It doesn't specify that the neighbors are within the subarray. Usually when we talk about peaks in an array, we refer to the original array. So a subarray "has a peak element" if it contains an element that is greater than its immediate neighbors in the original array. That's a different problem. For example, consider array [1,2,1]. The element at index 1 is a peak. Subarrays that contain index 1: [1,2,1] (full), [2,1], [1,2]. Also possibly [2]? That's just the element itself but it's a peak? The element 2 is a peak in the original array because it's greater than its neighbors 1 and 1. So the subarray [2] contains that element, so it has a peak element. According to our earlier interpretation, [2] would not count because it's not interior in the subarray. Which interpretation is more natural? The problem statement says "subarrays that have a 'peak' element." It might be interpreted as subarrays that contain a peak element (i.e., an index that is a peak in the original array). Because if you think about a subarray, its elements are just a subset of the original array. So if an element is a peak in the original, it's still a peak in the subarray? Not necessarily: In the subarray, that element's neighbors may be different because the subarray might not include the original neighbors. So the property "greater than its neighbors" might be evaluated based on the subarray's neighbors, not the original. Usually when we say "a peak element" we refer to that element's property in the context of the whole array. But if we take a subarray, the element's neighbors in the subarray might not be the same as its original neighbors. So the phrase "has a peak element" could be ambiguous.
Let's examine typical problems: There is a known LeetCode problem "Number of Subarrays with Peak Element" (maybe 2212? Actually LeetCode 2212 "Maximum Points in an Archery Competition"? No). I recall a problem "Count subarrays with peak element" might be from Codeforces? I'm not sure. Let's think: The typical concept of a peak in a subarray is that it's greater than its immediate neighbors within that subarray. That's a common subarray property (like "mountain subarray", "peak subarray"). However, they usually define a subarray that is a "peak" itself, not subarrays that contain a peak. For example, "Count the number of subarrays that have a peak element" could mean count subarrays where there exists an element that is a peak relative to the subarray. This is what we solved.
But it's also possible they meant: Count subarrays that contain at least one index i that is a peak in the original array. That would be simpler: answer = total subarrays that contain at least one peak index. That's just total subarrays minus subarrays that avoid all peak indices. That's a different counting problem. Let's see which one is more typical. I've seen problems like "Count subarrays with at least one peak" where peak is defined as element greater than its neighbors (in the original). Actually I recall a problem: "Given an array, count the number of subarrays that contain at least one peak element." This is similar to counting subarrays that contain a certain set of positions. That would be: we have a set of "good" indices (peaks). Count subarrays that include at least one of those indices. That's a standard problem: total subarrays minus subarrays that contain none of the good indices. And subarrays that contain none of the good indices are those where the subarray lies entirely within a segment of consecutive non-peak positions. That count can be computed by summing len(segment)*(len(segment)+1)/2 over all segments between peaks (including edges). That's a common technique.
But our current complement counting was different: we counted subarrays that have no interior peak, which allowed peaks at endpoints. But if we just want subarrays that contain at least one peak index (anywhere in subarray), then the complement is subarrays that contain no peak index at all (i.e., avoid all peak indices entirely). That's different from our interior condition. For example, in array [2,5,2] with peak at index 1. Subarrays that contain the peak: [5], [2,5], [5,2], [2,5,2] => 4 subarrays. But subarrays with interior peak (our interpretation): only [2,5,2] => 1. That's a big difference. So which one is likely? Let's analyze the wording: "subarrays that have a 'peak' element. A peak is an element greater than its neighbors." It doesn't say "relative to the subarray" explicitly. Usually when we talk about a property of an element within a subarray, we refer to its neighbors within that subarray. Because otherwise, the property is defined on the whole array, and the subarray simply inherits that property if it includes the element, but the neighbors considered are still the original ones, which might not all be in the subarray. But the phrase "neighbors" could be ambiguous. However, in many algorithmic problems, if they say "peak element", they usually mean in the context of the array being considered. For a subarray, the context is that subarray itself, so neighbors are the adjacent elements within that subarray. If they wanted the original definition, they might say "an element that is a peak in the original array." But they didn't specify "original". Usually they'd say "A peak element is an element that is greater than its immediate neighbors." That's a property of the element in the array. A subarray is a contiguous part of the array. If we consider the subarray as an array on its own, its neighbors are within the subarray. So it's natural to treat the subarray as its own array. So I think our interpretation is correct: the peak condition is with respect to the subarray's own neighbors.
But we need to be careful: The problem might be from a source where they define peak as an element that is greater than its immediate neighbors in the original array, and then ask to count subarrays that contain at least one such element. That is also a common problem: "Count subarrays containing at least one peak." However, they would probably say "contains a peak element" rather than "has a 'peak' element"? It's similar.
Let's see which interpretation yields a more interesting problem. Our solution using nextPeakAfter and complement counting is elegant but it's essentially counting subarrays with no interior peak. That's a bit non-trivial. The alternative "subarrays that contain at least one peak index" is also non-trivial but different: you just need to compute total subarrays minus those that lie entirely within gaps between peaks. That's also straightforward: If you have set of peak positions P, then the array is divided into segments of non-peak positions. For each segment of length L, number of subarrays entirely within that segment is L*(L+1)/2. Sum those and subtract from total. That's simpler. That would be O(n) as well. But is that too trivial? Possibly, but it's still a valid problem.
Which one is more likely given the phrasing? Let's parse: "subarrays that have a 'peak' element. A peak is an element greater than its neighbors." If we take a subarray, we consider its elements and their neighbors within that subarray? Usually when you talk about a subarray, you treat it as a smaller array. So you'd define peaks relative to that smaller array. But if you take a subarray that does not include both original neighbors, then the element might not be a peak within the subarray because it might have only one neighbor (if at boundary) and we typically require two neighbors to define a peak. So the element might not be considered a peak in the subarray. That would reduce the count. The problem might be more interesting if we have to consider the subarray's own structure. The alternative "contain a peak index" counts subarrays that include any original peak, regardless of position, which includes many short subarrays (like length 1 containing a peak). That's also interesting, but maybe simpler.
Let's see: In our interpretation, subarrays of length 1 or 2 cannot have a peak because they lack interior. So answer is 0 for n<3. That seems reasonable. In the alternative interpretation, subarray of length 1 that is a peak index would count. That could be many. Which one seems more natural? I'm not sure.
We need to look at the phrase: "A peak is an element greater than its neighbors." That is a definition of a peak element. Then "subarrays that have a 'peak' element" means subarrays that contain such an element. The element being a peak is a property of that element in the original array. It doesn't say "relative to the subarray". So I'd lean towards: an element that is a peak in the original array. Because if we consider the subarray in isolation, the element might not be a peak if one of its original neighbors is missing. But then the phrase "neighbors" would be ambiguous: in the subarray, the neighbors are the immediate adjacent elements in that subarray. But if we take a subarray that includes the peak index but cuts off one neighbor, then that element becomes boundary in the subarray, and does it have two neighbors to compare? It would have only one neighbor, so the definition "greater than its neighbors" might be considered vacuously false or undefined. Usually a peak is defined for positions with two neighbors, i.e., not the first or last element. So such an element would not be considered a peak within the subarray. So it would be less likely that they'd count that. So if they wanted to count subarrays that contain an element that is a peak in the original array, they'd need to specify that the peak property is with respect to the original array; otherwise, the element might not be a peak in the subarray. So to avoid confusion, they might have said "contains a peak element" and defined peak as an element greater than its neighbors (in the original array). But then they'd also need to consider that subarrays that include that element at the boundary still contain it, but it's not a peak in that subarray. But they don't care about subarray's definition; they just care that the element itself is a peak in the original. So [5] would be counted because the element 5 is a peak in the original. That seems plausible.
We need to decide which interpretation to answer. Since the problem statement we have is short, maybe it's from an interview question. I've seen a question: "Count subarrays that have at least one peak element" and they define peak as element greater than its neighbors. They usually expect you to compute total subarrays minus subarrays that lie strictly between peaks (i.e., subarrays that contain no peak index). That's a simpler solution. However, the solution we derived is also similar but different. Let's test with a simple case to see which one yields a nicer pattern. For array [1,2,1] peak at index1. Our algorithm (interior) yields answer=1 (only full array). The simpler "contains peak index" yields answer: any subarray that includes index1. Number of subarrays that include index1 = (1+1)(n-1)?? Actually number of subarrays containing a given index i is (i+1)(n-i). Because choose left endpoint L in [0,i] and right endpoint R in [i, n-1]. So for i=1, (1+1)(3-1)=22=4. That's [2], [1,2], [2,1], [1,2,1] => 4. Which one seems more typical? If the problem expects answer 4 for [1,2,1], then it's the contained-peak-index interpretation. But we don't know the expected answer.
We need to infer from typical coding problems. I recall a problem on LeetCode: "Number of Subarrays with Peak Element" is actually 2022 problem? Let's search memory: There is a problem "Count Subarrays with Peak Element" maybe from Codeforces Round? Actually there is a Codeforces problem "Peak" something. Hmm.
Let's think: In the interior interpretation, the answer for [1,2,1] is 1. That seems a bit low; maybe they'd want to count all subarrays where that peak is interior. But if they wanted to count subarrays that contain a peak, they'd get 4. Which is more interesting? Counting subarrays containing a given index is easy, but counting subarrays with at least one peak where peaks are multiple and overlapping is still easy: you can sum contributions with inclusion-exclusion or use the complement. But complement for "contain no peak index" is also easy: sum over gaps. So both are easy. But the interior version is slightly less trivial because the condition depends on endpoints relative to peaks. Actually the interior version we solved with a neat linear pass. It's also easy. So both are similar in difficulty.
But maybe there is a twist: For subarray to have a peak element, the element must be greater than its immediate neighbors within the subarray. That means that the subarray must include both neighbors of the peak (the original neighbors) to have the peak interior. So it's more restrictive. That's the version we solved.
Given that the problem explicitly says "Write a function to find the number of subarrays that have a 'peak' element." They didn't say "contains a peak element from the original array." They said "have a 'peak' element." I'd interpret that as: within that subarray, there exists an element that is a peak (i.e., greater than its neighbors within that subarray). That's a natural reading: "subarray has a peak" means the subarray itself has a peak element. So it's a property of the subarray, not just containing an element that is a peak in the larger array. So our interpretation is correct.
To be absolutely sure, let's see if any edge case would behave differently in both interpretations for a simple array like [2,1,2]. Our interpretation: no peaks because 1 is not > both neighbors. So answer 0. The other interpretation: are there any peak elements in original? Check indices: index0: only right neighbor, not peak; index1: 1<2 and <2? Actually 1<2 and <2, so not peak; index2: only left neighbor, not peak. So also 0. Same.
Array [2,3,1] peak at index1? 3>2 and >1 => yes. Our interior version: subarray must have L<1<R => L=0,R=2 only => [2,3,1] count=1. Other interpretation: all subarrays containing index1: (0,1): [2,3] (but subarray [2,3] length2, index1 is at right boundary, but is 3 a peak? In original, 3 is a peak, so the subarray contains a peak element. So would be counted. Similarly [3,1] contains index1, also counted. And [3] alone contains index1, counted. So 4 total. So big difference.
Which is more plausible? Usually when we say "subarray with peak element", we might think of a subarray that itself has a peak, meaning there is an element that is greater than its immediate neighbors in that subarray. That's a property like a "mountain" subarray. If you say "subarray that contains a peak element", that could be ambiguous, but I'd lean towards the subarray's own structure. For example, in LeetCode 941 "Valid Mountain Array" they define a mountain array as one that has a peak element. That's exactly: an array where there exists an index i (not ends) such that elements strictly increase up to i and then strictly decrease. That's about having a peak. So a subarray that is a "mountain" would have a peak. But the problem doesn't say mountain, just "has a peak element". That could mean there exists an interior element greater than its immediate neighbors. That's exactly the condition we used.
Therefore, I'll go with our interior peak version.
Now, we need to produce a solution that counts subarrays with at least one interior peak.
We have derived O(n) solution with O(1) extra space.
We should provide explanation:
-
Identify all peak indices in the original array. But note: For a peak to be a peak in a subarray, the subarray must include both its neighbors, i.e., the peak must be interior. So the property of a peak index is fixed in the original array.
-
Consider all subarrays. A subarray [L,R] contains an interior peak iff there exists a peak index p with L < p < R. We want number of such (L,R).
-
Instead of directly counting, count the complement: subarrays with no interior peak, i.e., for which no peak lies strictly inside. For a given L, what are the valid R? Let p be the smallest peak index > L (if any). If we choose R such that R <= p, then the open interval (L,R) does not contain any peak (since p is the first peak to the right, and it's not interior if R <= p). If we choose R > p, then p lies inside, so invalid. Thus for each L, the maximum allowed R is p (if exists) or n-1 (if no peak to the right). So number of valid R for this L is (p - L + 1) if p exists, else (n - L). This counts subarrays of any length, including those where L=R or length 2, etc.
-
Summing over all L gives total number of subarrays with no interior peak. Subtract from total subarrays n*(n+1)/2 yields answer.
-
We can compute this sum in a single right-to-left pass: maintain nextPeak (the smallest peak index seen so far to the right). Initialize nextPeak = n (no peak). For i from n-1 down to 0:
- The contribution for left endpoint i is (nextPeak - i + 1) if nextPeak < n, else (n - i).
- Add to totalNoPeak.
- If i is a peak (i.e., 1 <= i <= n-2 and nums[i] > nums[i-1] and > nums[i+1]), update nextPeak = i.
-
Finally answer = totalSubarrays - totalNoPeak.
Complexities: O(n) time, O(1) extra space.
We'll also note that for n<3 answer is 0, but algorithm handles it.
Now we'll produce Python code:
def count_peak_subarrays(nums):
n = len(nums)
total_sub = n * (n + 1) // 2
total_no_peak = 0
next_peak = n # sentinel: no peak to the right
for i in range(n-1, -1, -1):
if next_peak == n:
total_no_peak += n - i
else:
total_no_peak += next_peak - i + 1
# check if i is a peak (only if i has both neighbors)
if 0 < i < n-1 and nums[i] > nums[i-1] and nums[i] > nums[i+1]:
next_peak = i
return total_sub - total_no_peak
But careful: When we check if i is a peak, we should do it after using next_peak for i? Yes because for L=i we need nextPeakAfter[i] which is smallest peak > i, not including i itself. So we update next_peak after computing contribution. That's what we did.
Test with examples.
Edge: n=0 -> total_sub=0, total_no_peak=0, return 0. Fine.
Now let's test with earlier [1,2,1] (peak at 1). n=3:
Loop:
i=2: next_peak=3, add = 3-2=1, total_no_peak=1; i=2 not peak.
i=1: next_peak=3, add=3-1=2, total=3; i=1 peak => next_peak=1.
i=0: next_peak=1, add=1-0+1=2, total=5. total_no_peak=5, total_sub=6, answer=1. Good.
If we had [2,3,1] as earlier: same because peak at 1 only? Actually nums: [2,3,1]. Check: index1: 3>2 and >1 true. So same pattern, answer=1.
Now if we have [2,3,4,1]? Let's find peaks: index2? 4>3 and >1 true, so peak at 2. n=4. Subarrays with interior peak: need L<2<R => L in {0,1} and R in {3}? Actually R must be >2, so R can be 3 only because max index 3. So (0,3) and (1,3) => 2 subarrays. Also could L=0,R=3 and L=1,R=3. That's 2. Our algorithm: compute.
n=4, next=4.
i=3: add=4-3=1; total=1; not peak.
i=2: add=4-2=2; total=3; i=2 peak => next=2.
i=1: add=2-1+1=2; total=5; not peak.
i=0: add=2-0+1=3; total=8. total_no_peak=8, total_sub=10, answer=2. Good.
Now test with multiple peaks, like [1,2,1,2,1]? Actually peaks at index1 and index3? Let's see: index1: 2>1 and >1 true; index3: 2>1 and >1 true. So peaks at 1 and 3. n=5. Our earlier test with peaks at 1 and 3 gave answer 5. Let's verify manually: subarrays with interior peak: L<1=2 => R=2,3,4 => 3. L<3<R gives L<3, R>3 => L can be 0,1,2? Actually R must be >3 => R=4 only. So L=0,1,2 => 3 subarrays: (0,4),(1,4),(2,4). Overlap: (0,4) counted twice. Total distinct = 3+3-1=5. So answer=5. Our algorithm gave 5. Good.
Now consider array with three peaks: e.g., [1,3,1,5,1,4,1] maybe? Let's construct: indices: 1:3>1 and >1 -> peak; 3:5>1 and >1? neighbors: index2=1, index4=1 -> peak; 5:4>1 and >1? index4=1, index6=1 -> peak. So peaks at 1,3,5. n=7. Let's compute quickly with algorithm? Might be too much manually. But we can trust.
Now we should produce final answer with explanation and code.
But before final, let's double-check the logic of sum over L: We used that for each L, allowed R are from L to firstPeakAfter[L] inclusive. But is there any scenario where a subarray with L and R such that there is a peak in interior but it's not the first peak after L? That can't happen because if there's any peak in (L,R), then the smallest such peak is also in (L,R), and it would be firstPeakAfter[L] and it would be less than R. So invalid. So condition is both necessary and sufficient. So complement is correct.
Now we must ensure that the nextPeakAfter[L] computed is indeed the smallest peak > L. In our right-to-left pass, when we process i, next_peak is the smallest peak index > i (since we update when we see a peak). But is it the smallest? Suppose there are peaks at positions 3 and 5. When i=4, next_peak would be 5 (since we processed i=5 and set next_peak=5). That's the smallest >4. When i=3, before updating, next_peak=5, which is smallest >3? Actually there is also peak at 3 itself, but we want >3, so 5 is correct. After processing i=3 (if it's a peak), we set next_peak=3. For i=2, next_peak=3 (smallest >2). So correct.
Now the add formula: When next_peak == n, we add n - i. That gives count of R from i to n-1 inclusive: number = (n-1 - i + 1) = n-i. Yes.
When next_peak < n, we add next_peak - i + 1: R from i to next_peak inclusive: number = (next_peak - i + 1). Correct.
One more check: For L = next_peak itself? Suppose L = p (a peak). Then next_peak after L? In our algorithm at i=p, we compute contribution before updating next_peak to p? Actually when i=p, next_peak currently is the smallest peak > p? Let's simulate: Suppose peaks at 2 and 4. When i=4, next_peak initially maybe 6? Actually start n=6? Wait earlier n=6 example peaks at 2 and 4. Process i from 5 down to 0. At i=5, next=6, add=1, not peak. i=4: next=6, add=2, then because i=4 is peak, set next=4. So for L=4, the contribution used next_peak before update (which was 6) i.e., no peak to right. That's correct because for L=4, nextPeakAfter[4] should be none (since >4 there is none). So we used next_peak=6 (==n) to compute n-i. That's correct. So we must update next_peak after computing contribution, because for L=4, nextPeakAfter[4] should be first peak >4, not including 4 itself. So we must compute before updating. That matches our code.
Similarly for L=2: when i=2, next_peak currently is 4 (from previous update at i=4). That's the smallest peak >2. Good. Then after adding, we set next_peak=2 for left indices. So correct.
Thus code is correct.
Now we need to provide a clear explanation.
Potential pitfalls: Off-by-one errors for next_peak sentinel. Using n as sentinel is okay because peak indices are in [0,n-1]. When next_peak == n, treat as no peak.
Now we can produce final answer.
But the problem might also ask for function signature, maybe something like:
def countPeakSubarrays(nums: List[int]) -> int:
...
We'll write that.
Now I'll craft a thorough explanation.
However, let's also consider an alternative approach: Could there be subarrays where a non-peak element becomes a peak because one of its neighbors is not included? As argued, no, because for an element to be a peak in the subarray, it must have both neighbors in the subarray. So if we exclude one neighbor, the element is at an edge and cannot be a peak. So only elements that are peaks in the original array and are included with both neighbors can serve as peaks. So the set of candidate peaks is fixed.
Thus the problem reduces to counting subarrays that contain at least one such index as interior.
Now we should also note that a subarray can have multiple interior peaks. Our counting method avoids double counting by using complement.
Now I'll produce final answer.
But before final, I'd like to test the code with some random arrays to be sure. Let's write a quick mental test: random small n and brute force compare. But we trust.
Potential issues: The code might double count or mis-calc when n is large? Should be fine.
Now we must write the final answer in the required format: explanation and function.
I'll write in Python with type hints.
Now final.
We are given an array nums. We need to count how many contiguous subarrays contain at least one peak element, where a peak is an element that is strictly greater than both its immediate neighbors within that subarray. This means the peak must be an interior element of the subarray (it cannot be the first or last element of the subarray).
Key Observations
-
Fixed set of candidate peaks
For an index i to ever be a peak inside a subarray, it must satisfy the condition in the original array:
nums[i] > nums[i-1] and nums[i] > nums[i+1] (1 ≤ i ≤ n-2)
Because a subarray is contiguous, the neighbors of i inside the subarray are exactly the original indices i-1 and i+1. Hence the set of possible peak positions is determined solely by the original array.
-
When does a subarray contain a peak?
A subarray [L, R] (inclusive) contains a peak iff there exists a peak index p such that
L < p < R
i.e., p lies strictly inside the subarray.
-
Complementary counting
It is easier to count subarrays without an interior peak and subtract from the total number of subarrays n·(n+1)/2.
For a fixed left endpoint L, let nextPeak(L) be the smallest peak index that is strictly greater than L. If such a peak exists, any right endpoint R with R > nextPeak(L) would include that peak as an interior element, which is not allowed. Therefore the valid R values are exactly
L ≤ R ≤ nextPeak(L)
(the peak itself can be the right endpoint because it is then not interior).
If no peak exists to the right of L, any R up to n‑1 is allowed.
Hence, for a given L the number of valid subarrays without an interior peak is
count(L) = { nextPeak(L) - L + 1 if nextPeak(L) exists,
n - L otherwise }.
-
Efficient computation of nextPeak(L)
We can scan the array from right to left, maintaining the smallest peak seen so far.
- Initialise
next = n (meaning “no peak to the right”).
- For each position
i (from n‑1 down to 0):
- The value
next currently equals nextPeak(i).
- Add the corresponding
count(i) to the total.
- If
i itself is a peak, set next = i (for the next positions to the left).
Algorithm
function countPeakSubarrays(nums):
n = length of nums
totalSubarrays = n*(n+1)//2
totalNoPeak = 0
nextPeak = n // sentinel for “no peak to the right”
for i from n-1 down to 0:
if nextPeak == n:
totalNoPeak += n - i
else:
totalNoPeak += nextPeak - i + 1
// check if i is a peak in the original array
if 0 < i < n-1 and nums[i] > nums[i-1] and nums[i] > nums[i+1]:
nextPeak = i
return totalSubarrays - totalNoPeak
Correctness Proof
We prove that the algorithm returns the number of subarrays having at least one interior peak.
Lemma 1
A subarray [L,R] contains an interior peak iff there exists a peak index p with L < p < R.
Proof. By definition, a peak inside a subarray must be an element that is greater than its left and right neighbors within the subarray. Since the subarray is contiguous, these neighbors are exactly nums[p-1] and nums[p+1]. Thus p must satisfy the original peak condition and must be strictly inside the subarray. ∎
Lemma 2
For a fixed left endpoint L, let p = nextPeak(L) be the smallest peak index greater than L (or +∞ if none). Then a right endpoint R yields a subarray with no interior peak iff R ≤ p (interpreting p = +∞ as always satisfied).
Proof.
- (Sufficiency): If
R ≤ p, then every index q with L < q < R is < p, so q cannot be a peak (because p is the smallest peak > L). Hence the open interval (L,R) contains no peak, and the subarray has no interior peak.
- (Necessity): If
R > p, then p lies in (L,R) because L < p < R. Since p is a peak, the subarray contains an interior peak, violating the condition. ∎
Corollary
The number of R that produce a “no‑peak” subarray for this L is
p - L + 1 when p exists, otherwise n - L.
Lemma 3
During the right‑to‑left scan, at iteration i the variable next equals nextPeak(i).
Proof by induction on the loop.
Initially next = n, and for i = n-1 there is no peak index greater than n-1, so nextPeak(n-1) = n. After processing i, if i is a peak we set next = i; otherwise next remains the smallest peak seen to the right of i. For the next iteration i-1, the smallest peak > i-1 is exactly the current next (because any peak ≤ i is either i itself if it was a peak, or lies left of i-1). Hence the invariant holds. ∎
Lemma 4
totalNoPeak computed by the algorithm equals the total number of subarrays with no interior peak.
Proof. For each L = i, by Lemma 3 the value next at the start of the iteration equals nextPeak(i). The algorithm adds exactly count(i) (from the corollary) to totalNoPeak. Summing over all i gives the total number of (L,R) pairs with no interior peak. ∎
Theorem
totalSubarrays - totalNoPeak returned by the algorithm equals the number of subarrays containing at least one interior peak.
Proof. The set of all subarrays is partitioned into those with an interior peak and those without. Lemma 4 shows totalNoPeak counts the latter, so subtraction yields the former. ∎
Complexity Analysis
- Time: One pass over the array → O(n).
- Space: Only a few integer variables → O(1) (ignoring input storage).
Reference Implementation (Python)
from typing import List
def count_peak_subarrays(nums: List[int]) -> int:
"""
Returns the number of contiguous subarrays that contain at least one
interior peak element (element greater than both its immediate neighbors).
"""
n = len(nums)
total_sub = n * (n + 1) // 2
total_no_peak = 0
next_peak = n # sentinel meaning "no peak to the right"
# scan from right to left
for i in range(n - 1, -1, -1):
# add contribution for left endpoint i
if next_peak == n:
total_no_peak += n - i
else:
total_no_peak += next_peak - i + 1
# if i is a peak, update next_peak for positions to the left
if 0 < i < n - 1 and nums[i] > nums[i - 1] and nums[i] > nums[i + 1]:
next_peak = i
return total_sub - total_no_peak
The function follows exactly the algorithm proven correct above and runs in linear time with constant extra memory.