#3400
Medium Algorithms Maximum number of matching indices after right shifts
Array Two Pointers Simulation
84.8% acceptance
Mar 31, 2026
15
1
You are given two integer arrays, nums1 and nums2, of the same length.
An index i is considered matching if nums1[i] == nums2[i].
Return the maximum number of matching indices after performing any number of right shifts on nums1.
A right shift is defined as shifting the element at index i to index (i + 1) % n, for all indices.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn maximum_matching_indices(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
let n = nums1.len();
let mut best = 0;
for shift in 0..n {
let mut count = 0;
for i in 0..n {
if nums1[(i + n - shift) % n] == nums2[i] {
count += 1;
}
}
best = best.max(count);
}
best
}
}