To find the lexicographically largest palindromic substring (LLPS), we need to identify the
largest character in the string. We use a
frequency array of size
26 (for each lowercase letter) &
count the
frequency of each
character. Then, we
iterate from the end of
the frequency array to
find the largest
character and
print it
along with its count. This creates the longest possible palindromic substring with the largest
possible
character.
import java.util.Scanner; public class CF { public static void main(String[] args) { int[] arr = new int[26]; Scanner sc = new Scanner(System.in); String str = sc.next(); for(int i=0;i<str.length();i++){ char ch = str.charAt(i); arr[ch-'a']++; } for(int i=25;i>=0;i--){ if(arr[i]!=0){ while(arr[i]!=0){ char ch1 = (char)('a'+ i); System.out.print(ch1); arr[i]--; } break; } } } }
The algorithm iterates through the string once to count character frequencies and then iterates through the frequency array, resulting in a linear time complexity.
The algorithm uses a constant amount of extra space (a frequency array of size 26) to store character counts.