An integer is called balanced if it satisfies both of the following conditions:
It contains at least two digits.
The sum of digits at even positions is equal to the sum of digits at odd positions (the leftmost digit has position 1).
Return an integer representing the number of balanced integers in the range [low, high] (both inclusive).
Example 1:
Input:low = 1, high = 100
Output:9
Explanation:
The 9 balanced numbers between 1 and 100 are 11, 22, 33, 44, 55, 66, 77, 88, and 99.
Example 2:
Input:low = 120, high = 129
Output:1
Explanation:
Only 121 is balanced because the sum of digits at even and odd positions are both 2.
Example 3:
Input:low = 1234, high = 1234
Output:0
Explanation:
1234 is not balanced because the sum of digits at odd positions (1 + 3 = 4) does not equal the sum at even positions (2 + 4 = 6).
Constraints:
1 <= low <= high <= 1015
Solutions
Solution 1: Digit DP
First, if \(\textit{high} < 11\), there are no balanced integers in the range, so we directly return \(0\). Otherwise, we update \(\textit{low}\) to \(\max(\textit{low}, 11)\).
Then we design a function \(\textit{dfs}(\textit{pos}, \textit{diff}, \textit{lim})\), which represents processing the \(\textit{pos}\)-th digit of the number, where \(\textit{diff}\) is the difference between the sum of digits at odd positions and the sum of digits at even positions, and \(\textit{lim}\) indicates whether the current digit is constrained by the upper bound. The function returns the number of balanced integers that can be constructed from the current state.
The execution logic of the function is as follows:
If \(\textit{pos}\) exceeds the length of the number, it means all digits have been processed. If \(\textit{diff} = 0\), the current number is a balanced integer, return \(1\); otherwise, return \(0\).
Calculate the upper bound \(\textit{up}\) for the current digit. If constrained, it equals the current digit of the number; otherwise, it is \(9\).
Iterate through all possible digits \(i\) for the current position. For each digit \(i\), recursively call \(\textit{dfs}(\textit{pos} + 1, \textit{diff} + i \times (\text{1 if pos \% 2 == 0 else -1}), \textit{lim} \&\& i == \textit{up})\), and accumulate the results.
Return the accumulated result.
We first calculate the number of balanced integers \(\textit{a}\) in the range \([1, \textit{low} - 1]\), then calculate the number of balanced integers \(\textit{b}\) in the range \([1, \textit{high}]\), and finally return \(\textit{b} - \textit{a}\).
To avoid redundant calculations, we use memoization to store previously computed states.
The time complexity is \(O(\log^2 M \times D^2)\), and the space complexity is \(O(\log^2 M \times D)\). Here, \(M\) is the value of \(\textit{high}\), and \(D = 10\).