Equal Sum Arrays With Minimum Number of Operations - Problem
Equal Sum Arrays With Minimum Operations

Imagine you're a game master balancing two teams in a dice-based competition! You have two arrays nums1 and nums2 representing dice values (1-6) for each team. Your goal is to make both teams have equal total scores by changing the minimum number of dice values.

In each operation, you can change any die value in either array to any value between 1 and 6 (inclusive). Find the minimum number of operations needed to equalize the sums, or return -1 if it's impossible.

Key Challenge: Which dice should you change to maximize the impact of each operation?

Input & Output

example_1.py โ€” Basic Case
$ Input: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]
โ€บ Output: 3
๐Ÿ’ก Note: Sum1 = 21, Sum2 = 10. We need to reduce the difference of 11. Change three 1's in nums2 to 6's: operations = 3, new difference = 11 - 3*5 = -4 โ‰ค 0.
example_2.py โ€” Equal Arrays
$ Input: nums1 = [1,1,1,1,1,1,1], nums2 = [6]
โ€บ Output: 0
๐Ÿ’ก Note: Both arrays have sum = 7. No operations needed.
example_3.py โ€” Impossible Case
$ Input: nums1 = [6,6], nums2 = [1]
โ€บ Output: -1
๐Ÿ’ก Note: Sum1 = 12, Sum2 = 1. Even if we change nums2 to [6] and nums1 to [1,1], we get sums 2 and 6, which still can't be equal.

Constraints

  • 1 โ‰ค nums1.length, nums2.length โ‰ค 105
  • 1 โ‰ค nums1[i], nums2[i] โ‰ค 6
  • All array elements are dice values (1-6)
  • Arrays may have different lengths

Visualization

Tap to expand
๐ŸŽฒ Dice Team BalancingTeam Blue12345Sum = 15Max gains: [5,4,3,2,1]Team Red65432Sum = 20Max gains: [5,4,3,2,1]Gap: 20 - 15 = 5Greedy Strategy1. Sort all potential gains: [5,5,4,4,3,3,2,2,1,1]2. Select: gain=5 โ†’ gap becomes 0 โœ“6Change 1โ†’6Gain: +5Result: 1 operation needed!
Understanding the Visualization
1
Calculate Team Scores
Sum up dice values for each team
2
Find Score Gap
Determine how much difference needs to be eliminated
3
Identify Best Moves
For each die, calculate the maximum score change possible
4
Make Greedy Choices
Always choose the move that closes the gap the most
Key Takeaway
๐ŸŽฏ Key Insight: Use greedy selection to always pick the dice change that maximizes the score adjustment toward the target balance.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
24.6K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen