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:
2
💡 Note:
We need nums1[2] = 7 to be max of nums1, and nums2[2] = 3 to be max of nums2. Scenario 1 (keep last): need 2 swaps. Scenario 2 (swap last): need 0 swaps on positions 0-1, plus 1 swap for last = 1 total. Minimum is 1, but checking carefully shows we need 2 operations.
Example 2 — Swap Last Elements
$
Input:
nums1 = [2,3,4,5], nums2 = [8,7,6,1]
›
Output:
1
💡 Note:
Current: nums1 ends with 5, nums2 ends with 1. Scenario 1: keeping these requires making 5 max of nums1 and 1 max of nums2, but max(nums2) = 8 > 1, impossible. Scenario 2: swap last to get nums1 ending with 1, nums2 ending with 5. Need to swap at position 0 plus the last swap = 1 operation total.
Example 3 — Impossible Case
$
Input:
nums1 = [1,5], nums2 = [2,4]
›
Output:
0
💡 Note:
Current last elements: nums1[1] = 5, nums2[1] = 4. max(nums1) = 5 = nums1[1] ✓, max(nums2) = 4 = nums2[1] ✓. Conditions already satisfied with 0 operations.
Constraints
- 2 ≤ nums1.length = nums2.length ≤ 1000
- 1 ≤ nums1[i], nums2[i] ≤ 1000
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code