You are given two integers num1 and num2 representing an inclusive range [num1, num2].
The waviness of a number is defined as the total count of its peaks and valleys:
A digit is a peak if it is strictly greater than both of its immediate neighbors.
A digit is a valley if it is strictly less than both of its immediate neighbors.
The first and last digits of a number cannot be peaks or valleys.
Any number with fewer than 3 digits has a waviness of 0.
Return the total sum of waviness for all numbers in the range [num1, num2].
Example 1:
Input:num1 = 120, num2 = 130
Output:3
Explanation:
In the range [120, 130]:
120: middle digit 2 is a peak, waviness = 1.
121: middle digit 2 is a peak, waviness = 1.
130: middle digit 3 is a peak, waviness = 1.
All other numbers in the range have a waviness of 0.
Thus, total waviness is 1 + 1 + 1 = 3.
Example 2:
Input:num1 = 198, num2 = 202
Output:3
Explanation:
In the range [198, 202]:
198: middle digit 9 is a peak, waviness = 1.
201: middle digit 0 is a valley, waviness = 1.
202: middle digit 0 is a valley, waviness = 1.
All other numbers in the range have a waviness of 0.
Thus, total waviness is 1 + 1 + 1 = 3.
Example 3:
Input:num1 = 4848, num2 = 4848
Output:2
Explanation:
Number 4848: the second digit 8 is a peak, and the third digit 4 is a valley, giving a waviness of 2.
Constraints:
1 <= num1 <= num2 <= 1015
Solutions
Solution 1: Digit DP
Thinking
The bound is \(10^{15}\), so per-number simulation no longer works. The range sum is \(calc(num2)-calc(num1-1)\). Filling digits from the high end, peaks and valleys depend only on the last two written digits. The DP state stores the position, those two digits, whether the number has started, and whether it is tight, and it accumulates both the count and the waviness.
We need the total waviness of all numbers in \([num1, num2]\). Convert the range query to \(calc(num2) - calc(num1 - 1)\), where \(calc(x)\) is the total waviness in \([1, x]\).
Use digit DP from the most significant digit. Let \(dfs(pos, prev2, prev1, started, limit)\) be the number of valid numbers and their total waviness when we are filling position \(pos\), the previous two digits are \(prev2\) and \(prev1\) (use \(10\) if a digit is not yet filled), \(started\) indicates whether a non-leading zero has been placed, and \(limit\) indicates whether we are still bounded by the upper limit.
Enumerate the current digit \(d\). If at least two digits have been placed and \(prev1\) is strictly greater (or smaller) than both \(prev2\) and \(d\), then \(prev1\) is a peak (or valley) and contributes \(1\) to waviness, multiplied by the number of ways to fill the remaining digits.
The time complexity is \(O(\log x)\), and the space complexity is \(O(\log x)\), where \(x\) is the upper bound.