1460. Peaked Mountain Ranges
A hiker draws a trail profile as a path of 2 * n unit strokes: n up-strokes and n down-strokes, starting and ending on the ground line and never dipping below it. A peak is an up-stroke immediately followed by a down-stroke. Given n and the target number of peaks k, return how many different profiles have exactly k peaks, modulo 1000000007. If k is below 1 or above n, no profile qualifies and the answer is 0. Enumerating profiles is impossible for large n, so use factorials, inverse factorials and a modular inverse of n for O(n) time and O(n) space.
Example 1
- Input:
- n = 3, k = 2
- Output:
- 3
- Explanation:
Of the five profiles with three up-strokes and three down-strokes, exactly three have two peaks.
Example 2
- Input:
- n = 2, k = 2
- Output:
- 1
- Explanation:
Only the profile up, down, up, down has two peaks.
Example 3
- Input:
- n = 4, k = 5
- Output:
- 0
- Explanation:
A profile with 4 up-strokes cannot have 5 peaks, so the answer is 0.
Constraints
1 ≤ n ≤ 106
0 ≤ k ≤ 106
The result is taken modulo 109 + 7.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)