Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Minimizing Cost to Equalize Digit Frequency in an Array

Tech 2

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();
    }
}
Tags: Java

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.