java.lang.Object
g2501_2600.s2541_minimum_operations_to_make_array_equal_ii.Solution

public class Solution extends Object
2541 - Minimum Operations to Make Array Equal II.<p>Medium</p> <p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of equal length <code>n</code> and an integer <code>k</code>. You can perform the following operation on <code>nums1</code>:</p> <ul> <li>Choose two indexes <code>i</code> and <code>j</code> and increment <code>nums1[i]</code> by <code>k</code> and decrement <code>nums1[j]</code> by <code>k</code>. In other words, <code>nums1[i] = nums1[i] + k</code> and <code>nums1[j] = nums1[j] - k</code>.</li> </ul> <p><code>nums1</code> is said to be <strong>equal</strong> to <code>nums2</code> if for all indices <code>i</code> such that <code>0 <= i < n</code>, <code>nums1[i] == nums2[i]</code>.</p> <p>Return <em>the <strong>minimum</strong> number of operations required to make</em> <code>nums1</code> <em>equal to</em> <code>nums2</code>. If it is impossible to make them equal, return <code>-1</code>.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> nums1 = [4,3,1,4], nums2 = [1,3,7,1], k = 3</p> <p><strong>Output:</strong> 2</p> <p><strong>Explanation:</strong> In 2 operations, we can transform nums1 to nums2.</p> <p>1<sup>st</sup> operation: i = 2, j = 0. After applying the operation, nums1 = [1,3,4,4].</p> <p>2<sup>nd</sup> operation: i = 2, j = 3. After applying the operation, nums1 = [1,3,7,1]. One can prove that it is impossible to make arrays equal in fewer operations.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> nums1 = [3,8,5,2], nums2 = [2,4,1,6], k = 1</p> <p><strong>Output:</strong> -1</p> <p><strong>Explanation:</strong> It can be proved that it is impossible to make the two arrays equal.</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length == nums2.length</code></li> <li><code>2 <= n <= 10<sup>5</sup></code></li> <li><code>0 <= nums1[i], nums2[j] <= 10<sup>9</sup></code></li> <li><code>0 <= k <= 10<sup>5</sup></code></li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • minOperations

      public long minOperations(int[] nums1, int[] nums2, int k)