Equal Sum Arrays With Minimum Number of Operations - Problem
You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive.
In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive.
Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1 if it is not possible to make the sum of the two arrays equal.
Input & Output
Example 1 — Basic Case
$
Input:
nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]
›
Output:
3
💡 Note:
Sum of nums1 is 21, sum of nums2 is 10. We need to reduce difference of 11. Change nums1[4] from 5→1 (gain 4), nums1[3] from 4→1 (gain 3), nums1[2] from 3→1 (gain 2). Total gain = 9. Change nums2[0] from 1→3 (gain 2). Total operations = 4, but we only need 3 to reduce difference to 0.
Example 2 — Equal Sums
$
Input:
nums1 = [1,1,1,1,1,1,1], nums2 = [6]
›
Output:
1
💡 Note:
Sum of nums1 is 7, sum of nums2 is 6. Difference is 1. Change any element in nums1 from 1→0 is invalid, but change nums2[0] from 6→7 is invalid too. Actually, change nums1[0] from 1→2 reduces difference by -1, making sums equal. Wait, let me recalculate: change nums2[0] from 6→7 isn't valid since max is 6. Change nums1[6] from 1→0 isn't valid since min is 1. We can change nums2[0] from 6→5 (reduces sum by 1) or change nums1 element from 1→2 (increases sum by 1). Either takes 1 operation.
Example 3 — Impossible Case
$
Input:
nums1 = [6,6], nums2 = [1]
›
Output:
-1
💡 Note:
nums1 sum is 12, nums2 sum is 1. Maximum possible sum for nums2 is 1×6=6, minimum possible sum for nums1 is 2×1=2. Since max of nums2 (6) < min of nums1 (2), it's impossible to equalize.
Constraints
- 1 ≤ nums1.length, nums2.length ≤ 105
- 1 ≤ nums1[i], nums2[i] ≤ 6
Visualization
Tap to expand
Understanding the Visualization
1
Input Arrays
Two arrays with different sums, elements range 1-6
2
Calculate Strategy
Find which changes give maximum impact
3
Apply Changes
Minimum operations to equalize sums
Key Takeaway
🎯 Key Insight: Greedily prioritize changes that provide maximum reduction in sum difference
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code