Skip to main content
Back to problems
#1775
Medium Algorithms

Equal sum arrays with minimum number of operations

Array Hash Table Greedy Counting
54.6% acceptance
Feb 25, 2026
964
49
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_operations(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
    let sum1: i32 = nums1.iter().sum();
    let sum2: i32 = nums2.iter().sum();
    // Ensure sum1 <= sum2 (swap if needed)
    let (nums1, nums2, mut diff) = if sum1 <= sum2 {
      (nums1, nums2, sum2 - sum1)
    } else {
      (nums2, nums1, sum1 - sum2)
    };
    if diff == 0 { return 0; }
    // Impossible check: max achievable sum1 = 6*len1, min of sum2 = 1*len2
    // Already handled: if diff can't be covered
    // Gains: how much each element can contribute to closing the gap
    // From nums1 (currently lower): each v can increase by (6-v)
    // From nums2 (currently higher): each v can decrease by (v-1)
    let mut gains: Vec<i32> = nums1.iter().map(|&v| 6 - v)
      .chain(nums2.iter().map(|&v| v - 1))
      .collect();
    gains.sort_unstable_by(|a, b| b.cmp(a)); // descending

    let mut ops = 0;
    for gain in gains {
      if diff <= 0 { break; }
      diff -= gain;
      ops += 1;
    }
    if diff > 0 { -1 } else { ops }
  }
}