Leetcode 2541: Minimum Operations to Make Array Equal II

grid47
grid47
Exploring patterns and algorithms
Feb 26, 2024 7 min read

You are given two integer arrays nums1 and nums2 of equal length n and an integer k. You can perform the following operation on nums1: Choose two indexes i and j and increment nums1[i] by k and decrement nums1[j] by k. The goal is to determine the minimum number of operations required to make nums1 equal to nums2. If it is impossible, return -1.
Problem
Approach
Steps
Complexity
Input: The input consists of two integer arrays `nums1` and `nums2` of equal length `n` and an integer `k`.
Example: nums1 = [3, 7, 4], nums2 = [1, 7, 8], k = 2
Constraints:
• n == nums1.length == nums2.length
• 2 <= n <= 10^5
• 0 <= nums1[i], nums2[i] <= 10^9
• 0 <= k <= 10^5
Output: The output should be the minimum number of operations required to make `nums1` equal to `nums2`. If it is impossible, return `-1`.
Example: 2
Constraints:
• The result should be an integer or -1 if it is impossible.
Goal: To transform `nums1` into `nums2` using the fewest number of operations.
Steps:
• For each index `i`, compute the difference `nums1[i] - nums2[i]`.
• If the difference is not divisible by `k`, return `-1` because it is impossible to reach the target.
• For all valid differences, keep track of the sum of positive differences and negative differences.
• If the sum of differences is not zero, return `-1`.
• Otherwise, return the total number of operations, which is the sum of all positive differences divided by `k`.
Goal: Ensure that the solution works efficiently within the given constraints.
Steps:
• Arrays `nums1` and `nums2` have equal lengths.
• The values of `k` are non-negative integers, and both arrays may contain large values.
Assumptions:
• Both arrays `nums1` and `nums2` are valid and have the same length.
• The array elements are integers within the range of `0` to `10^9`.
Input: [3, 7, 4], [1, 7, 8], k = 2
Explanation: We can increment `nums1[0]` by 2 and decrement `nums1[2]` by 2 in the first operation. Then, we increment `nums1[2]` by 2 and decrement `nums1[0]` by 2 in the second operation to match `nums2`.

Input: [3, 6, 2], [2, 5, 1], k = 1
Explanation: It is impossible to make the arrays equal because the differences between corresponding elements are not divisible by `k = 1`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus