Advertisement
exmkg

Untitled

Oct 27th, 2024
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. class Solution {
  2.     public int minOperations(int[] nums1, int[] nums2) {
  3.         if (nums1.length > nums2.length * 6 ||
  4.             nums2.length > nums1.length * 6) {
  5.             return -1;
  6.         }
  7.         int sum1 = 0;
  8.         int sum2 = 0;
  9.         for (int x : nums1) sum1 += x;
  10.         for (int x : nums2) sum2 += x;
  11.  
  12.         if (sum1 > sum2) { // swap(nums1, nums2) and swap(sum1, sum2)
  13.             int[] temp = nums1; nums1 = nums2; nums2 = temp;
  14.             int tempSum = sum1; sum1 = sum2; sum2 = tempSum;
  15.         } // Make sure that nums1 and nums2 are so that sum1 < sum2
  16.  
  17.         PriorityQueue<Integer> pq1 = new PriorityQueue<>(); // default ordering, small -> large
  18.         PriorityQueue<Integer> pq2 = new PriorityQueue<>(Collections.reverseOrder()); // large -> small
  19.         for (int x : nums1) pq1.offer(x);
  20.         for (int x : nums2) pq2.offer(x);
  21.  
  22.         int operations = 0;
  23.         for (; sum1 < sum2; operations++) {
  24.             if (pq2.isEmpty() || pq2.peek() - 1 < 6 - pq1.peek()) {
  25.                 // if (it is best to increase the smallest number from nums1)
  26.                 sum1 += 6 - pq1.poll();
  27.             } else {
  28.                 // else (it is best to decrease the largest number from nums2)
  29.                 sum2 -= pq2.poll() - 1;
  30.             }
  31.         }
  32.         return operations;
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement