Sunday, August 17, 2025

 Problem: 

Given a string containing some characters from ‘a’ to ‘z’ with repetitions, find the maximum frequency deviation between character occurrences where the deviation is computed as the difference between the frequencies of the most occurring character and the least occurring character.  

import java.util.*; 

import java.lang.*; 

import java.io.*; 

class Ideone 

{ 

public static void main (String[] args) throws java.lang.Exception 

{ 

System.out.println(getMaxDiffFrequencyDistribution("abcdeefggggghhhiij")); 

} 

private static int getMaxDiffFrequencyDistribution(String input) 

{ 

int max = Integer.MIN_VALUE; 

int min = max; 

int diff = max – min; 

Map<Character, Integer> countMap = new HashMap<Character, Integer>(); 

for (int i = 0; i < input.length(); i++) 

{ 

int val = 1; 

if (countMap.containsKey(input.charAt(i)) { 

val = countMap.get(input.charAt(i)); 

val += 1; 

} 

else { 

min = 1; 

} 

 

if (val > max) { 

max = val; 

} 

countMap.put(input.charAt(i), val); 

} 

If (max – min > diff) { 

diff = max – min; 

} 

return diff; 

} 

} 

 

Test Case 

“a” => 0 

abcdeefggggghhhiij” => 4 

 

 

 

 

 

No comments:

Post a Comment