Number of ZigZag Arrays I
Real-world version: Counting Sawtooth Brightness ProgramsThe statement here is our own: the same inputs, outputs and technique.
A light bar carries n cells in a row. A program assigns every cell an integer brightness in the closed range [l, r], so a program is an array a of length n with l <= a[i] <= r.
A program is a sawtooth when the brightness turns around at every cell it can:
- no two neighbouring cells share a brightness, so
a[i] != a[i - 1]for everyi >= 1; - the direction alternates, so for every
iwith1 <= i <= n - 2exactly one ofa[i - 1] < a[i] > a[i + 1]anda[i - 1] > a[i] < a[i + 1]holds.
Both opening directions are allowed: a program may start by going up or by going down.
Return how many sawtooth programs exist, taken modulo 10^9 + 7.
Examples
Example 1
- Input
- n = 3, l = 1, r = 2
- Output
- 2
Only [1, 2, 1] and [2, 1, 2] turn around at the middle cell; the six other programs over two brightness values repeat a neighbour somewhere.
Example 2
- Input
- n = 3, l = 1, r = 3
- Output
- 10
The count includes peaks such as [1, 3, 2] and troughs such as [3, 1, 2], and the reported figure is already below the modulus.
Example 3
- Input
- n = 4, l = 2, r = 4
- Output
- 16
One valid program is [2, 4, 3, 4], which rises, falls, rises; the figure returned counts every such program of four cells over the brightness values 2, 3 and 4.
Example 4
- Input
- n = 6, l = 1, r = 2
- Output
- 2
The two programs counted are [1, 2, 1, 2, 1, 2] and [2, 1, 2, 1, 2, 1]; each of the six cells sits in range and every step reverses the previous one.
Constraints
- 3 <= n <= 2000
- 1 <= l < r <= 2000
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def sawtooth_programs(length: int, low: int, high: int) -> int:public int sawtoothPrograms(int length, int low, int high)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 8 test cases: 8 passed
- Passed: 4 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Stone Game IIReal-world version: Front Loaded Tray HaulMedium
- Jump Game VIIReal-world version: Pontoon Crossing With A Hop RangeMedium
- Find All Possible Stable Binary Arrays IReal-world version: Settled Control TapesMedium
- Maximum Frequency After Subarray OperationReal-world version: Most Dials Reading k After One NudgeMedium