Given two integers L and R denoting a range [L, R]. The task is to find the total count of numbers in the given range [L,R] whose sum of even digits is greater than the sum of odd digits.
Input : L=2 R=10
Output : 4
Numbers having the property that sum of even
digits is greater than sum of odd digits are: 2, 4, 6, 8
Input : L=2 R=17
Output : 7
Firstly, count the required numbers up to R i.e. in the range [0, R]. To reach the answer in the range [L, R] solve for the range from zero to R and then subtracting the answer for the range from zero to L – 1. Define the DP states as follows:
- Consider the number as a sequence of digits, one state is the position at which we are currently at. This position can have values from 0 to 18 if we are dealing with the numbers up to 10^18. In each recursive call, try to build the sequence from left to right by placing a digit from 0 to 9.
- First state is the sum of the even digits that has been placed so far.
- Second state is the sum of the odd digits that has been placed so far.
- Another state is the boolean variable tight which tells the number we are trying to build has already become smaller than R so that in the upcoming recursive calls we can place any digit from 0 to 9. If the number has not become smaller, the maximum limit of digit we can place is the digit at the current position in R.
Below is the implementation of the above approach:
Time Complexity : There would be at max 18*(180)*(180)*2 computations when 0 < a,b < 1018
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.