Untitled

 avatar
unknown
java
a year ago
1.7 kB
10
Indexable
import java.util.*;

class Solution {
    public int solution(int[] A, int[] B) {
        int sumA = 0, sumB = 0;
        for (int num : A)
            sumA += num;
        for (int num : B)
            sumB += num;
        
        int diff = Math.abs(sumA - sumB);
        
        // If the difference between sums is odd, it's impossible to make them equal
        if (diff % 2 != 0)
            return -1;
        
        // Calculate the target sum for both arrays
        int target = diff / 2;
        
        // Count occurrences of each number in A
        int[] countA = new int[7]; // Extra space for indexing from 1 to 6
        for (int num : A)
            countA[num]++;
        
        // Iterate through each possible value that could be obtained by changing the face of a die in B
        for (int num : B) {
            int potentialNewSumB = sumB - num + target;
            if (potentialNewSumB >= 1 && potentialNewSumB <= 6) {
                int neededInA = Math.abs(countA[potentialNewSumB]);
                if (neededInA > 0)
                    return Math.abs(countA[potentialNewSumB]); // Minimum number of dice to be turned
            }
        }
        
        return -1; // No solution found
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        // Test cases
        System.out.println(solution.solution(new int[]{5}, new int[]{1, 1, 6})); // 1
        System.out.println(solution.solution(new int[]{2, 3, 1, 1, 2}, new int[]{5, 4, 6})); // 2
        System.out.println(solution.solution(new int[]{5, 4, 1, 2, 6, 5}, new int[]{2})); // 6
        System.out.println(solution.solution(new int[]{1, 2, 3, 4, 3, 2, 1}, new int[]{6})); // -1
    }
}
Editor is loading...
Leave a Comment