Minimizing Cost to Equalize Digit Frequency in an Array
Given an array of length n (where n is a multiple of 10), each element is a integer between 0 and 9. The goal is to modify some elements so that each digit from 0 to 9 appears exactly n/10 times. Changing the value at position i has an associated cost b_i. The objective is to find the minimal total cost required to achieve equal frequency for all digits.
Input Format The first line contains a positvie integer n. The following n lines each contain two integers a_i and b_i, separated by a space.
10
1 1
1 2
1 3
2 4
2 5
2 6
3 7
3 8
3 9
4 10
Output Format Output a single integer represanting the minimal total cost.
27
Explanation Modifying the elements at positions 1, 2, 4, 5, 7, and 8 results in a total cost of 1 + 2 + 4 + 5 + 7 + 8 = 27.
Java Implementation
import java.util.*;
public class DigitFrequencyBalancer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[][] data = new int[n][2];
int[] freqCount = new int[10];
int targetFreq = n / 10;
int totalCost = 0;
for (int i = 0; i < n; i++) {
data[i][0] = input.nextInt();
data[i][1] = input.nextInt();
freqCount[data[i][0]]++;
}
Arrays.sort(data, (x, y) -> Integer.compare(x[1], y[1]));
for (int j = 0; j < n; j++) {
int currentDigit = data[j][0];
if (freqCount[currentDigit] > targetFreq) {
totalCost += data[j][1];
freqCount[currentDigit]--;
}
}
System.out.println(totalCost);
input.close();
}
}