โ† All problems

3751. Total Waviness of Numbers in Range I

MediumOpen on LeetCodeProblem statement

Problem Statement

3751. Total Waviness of Numbers in Range I

Medium


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:

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]:

Thus, total waviness is 1 + 1 + 1 = 3.

Example 2:

Input: num1 = 198, num2 = 202

Output: 3

Explanation:

In the range [198, 202]:

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:

Java โ€” naive

Source file
class Solution {
    public int totalWaviness(int num1, int num2) {
        int total = 0;
        for (int i = num1; i <= num2; i++)
            total += waviness(String.valueOf(i));
        return total;
    }

    int waviness(String s) {
        int n = s.length(), wav = 0;
        for (int i = 1; i < n - 1; i++)
            if (s.charAt(i) > Math.max(s.charAt(i - 1), s.charAt(i + 1))
                    || s.charAt(i) < Math.min(s.charAt(i - 1), s.charAt(i + 1)))
                wav++;
        return wav;
    }
}