All problems
0530HardMathDynamic Programming

Total Turning Points in a Number Range

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3753Total Waviness of Numbers in Range II

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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