[LeetCode] Minimum Operations to Maximize Last Elements in Arrays

2934. Minimum Operations to Maximize Last Elements in Arrays

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 of nums1, i.e., nums1[n - 1] = max(nums1[0], nums1[1], ..., nums1[n - 1]).
  • nums2[n - 1] is equal to the maximum value among all elements of nums2, i.e., nums2[n - 1] = max(nums2[0], nums2[1], ..., nums2[n - 1]).

Return an integer denoting the minimum number of operations needed to meet both conditions, or -1 if it is impossible to satisfy both conditions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
int helper(vector<int>& A, vector<int>& B) {
int n = A.size(), ma1 = A.back(), ma2 = B.back();
int res = 0;
for(int i = 0; i < n-1; i++) {
if(A[i] <= ma1 and B[i] <= ma2) continue;
if(A[i] <= ma2 and B[i] <= ma1) res += 1;
else return 3 * n;
}
return res;
}
public:
int minOperations(vector<int>& nums1, vector<int>& nums2) {
int res = helper(nums1, nums2), n = nums1.size();
swap(nums1[n-1], nums2[n-1]);
res = min(res, 1 + helper(nums1,nums2));
if(res > 2 * n) return -1;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/11/12/PS/LeetCode/minimum-operations-to-maximize-last-elements-in-arrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.