Total Waviness of Numbers in Range I

medium math enumeration digits

Problem

Given an inclusive range [num1, num2], the waviness of a number is the count of its interior digits that are peaks or valleys. A digit is a peak if it is strictly greater than both neighbors, a valley if strictly less than both. The first and last digits never count, so numbers with fewer than 3 digits have waviness 0. Return the total waviness summed over every number in the range.

Inputnum1 = 120, num2 = 130
Output3
120, 121 and 130 each have one peak (the middle 2 or 3); all others are flat. 1 + 1 + 1 = 3.

def totalWaviness(num1, num2):
    total = 0
    for n in range(num1, num2 + 1):
        d = [int(ch) for ch in str(n)]   # digits of n
        for i in range(1, len(d) - 1):   # interior digits only
            peak = d[i] > d[i - 1] and d[i] > d[i + 1]
            valley = d[i] < d[i - 1] and d[i] < d[i + 1]
            if peak or valley:
                total += 1
    return total
function totalWaviness(num1, num2) {
  let total = 0;
  for (let n = num1; n <= num2; n++) {
    const d = String(n).split("").map(Number); // digits of n
    for (let i = 1; i < d.length - 1; i++) {    // interior digits
      const peak = d[i] > d[i - 1] && d[i] > d[i + 1];
      const valley = d[i] < d[i - 1] && d[i] < d[i + 1];
      if (peak || valley) total++;
    }
  }
  return total;
}
int totalWaviness(int num1, int num2) {
    int total = 0;
    for (int n = num1; n <= num2; n++) {
        char[] d = Integer.toString(n).toCharArray(); // digits
        for (int i = 1; i < d.length - 1; i++) {      // interior
            boolean peak = d[i] > d[i - 1] && d[i] > d[i + 1];
            boolean valley = d[i] < d[i - 1] && d[i] < d[i + 1];
            if (peak || valley) total++;
        }
    }
    return total;
}
int totalWaviness(int num1, int num2) {
    int total = 0;
    for (int n = num1; n <= num2; n++) {
        string d = to_string(n);              // digits of n
        for (int i = 1; i + 1 < (int)d.size(); i++) { // interior
            bool peak = d[i] > d[i - 1] && d[i] > d[i + 1];
            bool valley = d[i] < d[i - 1] && d[i] < d[i + 1];
            if (peak || valley) total++;
        }
    }
    return total;
}
Time: O((num2 − num1) · D) Space: O(D)