Show problems as
Classic problem #3753HardMathDynamic Programming

Total Waviness of Numbers in Range II

Real-world version: Total Turning Points in a Number Range
Tracked in this browser only
Read Total Waviness of Numbers in Range II on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Write a whole number in base ten with no leading zeros. One of its digits is a turning point when it has a digit on each side and it is either strictly larger than both of those neighbours or strictly smaller than both of them. The waviness of a number is how many of its digits are turning points, so any number below 100 has waviness 0.

Take 36269 as an illustration. Its middle digit 2 is smaller than the 6 on either side of it, and the first 6 is larger than the 3 before it and the 2 after it, so 36269 has waviness 2. The last 6 is not a turning point, since it is above the 2 before it but below the 9 after it.

Given low and high, add up the waviness of every whole number from low to high inclusive and return that sum reduced modulo 1000000007.

Examples

Example 1

Input
low = 121, high = 121
Output
1

The digits of 121 are 1, 2 and 1. The middle digit is larger than both neighbours, so it is a turning point and the range totals 1.

Example 2

Input
low = 95, high = 105
Output
5

The numbers from 95 to 99 have only two digits, so they add nothing. 100 has no turning point, while each of 101, 102, 103, 104 and 105 has its middle 0 below both neighbours, which totals 5.

Example 3

Input
low = 10101, high = 10101
Output
3

In 10101 the second, third and fourth digits each sit below or above both of their neighbours, so the waviness of this single number is 3.

Constraints

  • 1 <= low <= high <= 10^15
  • The answer is the sum reduced modulo 1000000007, so it stays below 10^9 + 7.

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.

Python
def total_waviness(low: int, high: int) -> int:
Java
public long totalWaviness(long low, long high)