#2934
Medium Algorithms Minimum operations to maximize last elements in arrays
Array Enumeration
43.9% acceptance
Feb 25, 2026
203
16
You are given two 0-indexed integer arrays, nums1 and nums2, both having length n.
In an operation, you select an index i in the range [0, n - 1] and swap nums1[i] and nums2[i].
Find the minimum number of operations required to satisfy:
nums1[n - 1] = max(nums1), nums2[n - 1] = max(nums2).
Return the minimum number of operations needed, or -1 if it is impossible.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn min_operations(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
let n = nums1.len();
let solve = |m1: i32, m2: i32| -> Option<i32> {
let mut ops = 0;
for i in 0..n - 1 {
let (a, b) = (nums1[i], nums2[i]);
if a <= m1 && b <= m2 {
// no swap needed
} else if b <= m1 && a <= m2 {
ops += 1; // swap
} else {
return None; // impossible
}
}
Some(ops)
};
let m1 = nums1[n - 1];
let m2 = nums2[n - 1];
// Case 1: don't swap last
let case1 = solve(m1, m2);
// Case 2: swap last (cost 1 + solve with swapped maxes)
let case2 = solve(m2, m1).map(|ops| ops + 1);
match (case1, case2) {
(Some(a), Some(b)) => a.min(b),
(Some(a), None) => a,
(None, Some(b)) => b,
(None, None) => -1,
}
}
}