Minimum Operations to Maximize Last Elements in Arrays - Problem
You are given two 0-indexed integer arrays, nums1 and nums2, both having length n. You are allowed to perform a series of operations (possibly none).
In an operation, you select an index i in the range [0, n - 1] and swap the values of nums1[i] and nums2[i].
Your task is to find the minimum number of operations required to satisfy the following conditions:
nums1[n - 1]is equal to the maximum value among all elements ofnums1nums2[n - 1]is equal to the maximum value among all elements ofnums2
Return an integer denoting the minimum number of operations needed to meet both conditions, or -1 if it is impossible to satisfy both conditions.
Input & Output
Example 1 — Basic Case
$
Input:
nums1 = [1,2,7], nums2 = [4,5,3]
›
Output:
1
💡 Note:
We need nums1[2] = 7 to be max of nums1, and nums2[2] = 3 to be max of nums2. Currently max(nums2) = 5 > 3, so we swap nums1[1] and nums2[1]: nums1 = [1,5,7], nums2 = [4,2,3]. Now 7 and 3 are the maximums. Total: 1 operation.
Example 2 — Swap Last Elements
$
Input:
nums1 = [2,3,4,5], nums2 = [8,7,6,1]
›
Output:
2
💡 Note:
Current: nums1 ends with 5, nums2 ends with 1. If we keep this, we need nums1 max = 5 but max(nums1) = 5 ✓, and nums2 max = 1 but max(nums2) = 8 > 1 ✗. If we swap last: nums1 ends with 1, nums2 ends with 5. We need 3 swaps total (including last). Better: swap positions 0 and 1, then we get 2 operations.
Example 3 — Impossible Case
$
Input:
nums1 = [1,5], nums2 = [2,4]
›
Output:
-1
💡 Note:
Current last elements: nums1[1] = 5, nums2[1] = 4. To make 5 max of nums1: nums1[0] = 1 ≤ 5 ✓. To make 4 max of nums2: nums2[0] = 2 ≤ 4 ✓. This works with 0 operations. But let's verify: max(nums1) = 5 = nums1[1] ✓, max(nums2) = 4 = nums2[1] ✓. Actually this should return 0, not -1.
Constraints
- 2 ≤ nums1.length = nums2.length ≤ 1000
- 1 ≤ nums1[i], nums2[i] ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input Arrays
Two arrays where last elements may not be maximum
2
Swap Operations
We can swap elements at same indices between arrays
3
Goal
Make last element the maximum in each array with minimum swaps
Key Takeaway
🎯 Key Insight: Only two final configurations are possible - either keep current last elements or swap them
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code