Longest set of Palindrome Numbers from the range [ L , R ] with at most K difference between its maximum and minimum | Java program for the above approach ; Function to find the maximum size of group of palindrome numbers having difference between maximum and minimum element at most K ; Stores the all the palindromic numbers in the range [ L , R ] ; Traverse over the range [ L , R ] ; If i is a palindrome ; Append the number in the list ; Stores count of maximum palindromic numbers ; Iterate each element in the list ; Calculate rightmost index in the list < current element + K ; Check if there is rightmost index from the current index ; Return the count ; Function to search the rightmost index of given number ; Store the rightmost index ; Calculate the mid ; If given number <= num ; Assign ans = mid ; Update low ; Update high ; return ans ; Function to check if the given number is palindrome or not ; Generate reverse of the given number ; If n is a palindrome ; Driver Code
import java . util . * ; public class Main { static int countNumbers ( int L , int R , int K ) { ArrayList < Integer > list = new ArrayList < > ( ) ; for ( int i = L ; i <= R ; i ++ ) { if ( isPalindrome ( i ) ) { list . add ( i ) ; } } int count = 0 ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { int right_index = search ( list , list . get ( i ) + K - 1 ) ; if ( right_index != - 1 ) count = Math . max ( count , right_index - i + 1 ) ; } return count ; } static int search ( ArrayList < Integer > list , int num ) { int low = 0 , high = list . size ( ) - 1 ; int ans = - 1 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( list . get ( mid ) <= num ) { ans = mid ; low = mid + 1 ; } else high = mid - 1 ; } return ans ; } static boolean isPalindrome ( int n ) { int rev = 0 ; int temp = n ; while ( n > 0 ) { rev = rev * 10 + n % 10 ; n /= 10 ; } return rev == temp ; } public static void main ( String args [ ] ) { int L = 98 , R = 112 ; int K = 13 ; System . out . print ( countNumbers ( L , R , K ) ) ; } }