#3753
Total Waviness of Numbers in Range II
HardMathDynamic ProgrammingDynamic ProgrammingDigit DP
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * d^2) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * d^2)Space O(n)
Use digit dynamic programming to efficiently count peaks and valleys without explicitly checking each number. This reduces redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Define a recursive function with parameters (position, tight, lastDigit, secondLastDigit) to explore digit placements.
- 2Step 2: Use memoization to store results for previously computed states to avoid re-computation.
- 3Step 3: Count peaks and valleys based on the current digit and its neighbors.
solution.py16 lines
1def countWaviness(num, pos, tight, lastDigit, secondLastDigit, memo):
2 if pos == len(num): return 0
3 if (pos, tight, lastDigit, secondLastDigit) in memo:
4 return memo[(pos, tight, lastDigit, secondLastDigit)]
5 limit = int(num[pos]) if tight else 9
6 total = 0
7 for digit in range(0, limit + 1):
8 if pos > 1:
9 if (digit > lastDigit and lastDigit > secondLastDigit) or (digit < lastDigit and lastDigit < secondLastDigit):
10 total += 1
11 total += countWaviness(num, pos + 1, tight and (digit == limit), digit, lastDigit, memo)
12 memo[(pos, tight, lastDigit, secondLastDigit)] = total
13 return total
14
15def totalWaviness(num1, num2):
16 return countWaviness(str(num2 + 1), 0, True, -1, -1, {}) - countWaviness(str(num1), 0, True, -1, -1, {})ℹ
Complexity note: The complexity arises from exploring each digit and its states, with memoization reducing redundant calculations.
- 1Understanding peaks and valleys is crucial for counting waviness.
- 2Dynamic programming can significantly optimize counting problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.