[LeetCode] Find the Longest Equal Subarray

2831. Find the Longest Equal Subarray

You are given a 0-indexed integer array nums and an integer k.

A subarray is called equal if all of its elements are equal. Note that the empty subarray is an equal subarray.

Return the length of the longest possible equal subarray after deleting at most k elements from nums.

A subarray is a contiguous, possibly empty sequence of elements within an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
int longestEqualSubarray(vector<int>& nums, int k) {
unordered_map<int, vector<int>> mp;
for(int i = 0; i < nums.size(); i++) {
mp[nums[i]].push_back(i);
}
int res = 0;
for(auto [_,vec] : mp) {
int l = 0, r = 0;
while(r < vec.size()) {
while(r < vec.size()) {
int cnt = r - l + 1;
int skip = vec[r] - vec[l] + 1 - cnt;
if(skip <= k) {
res = max(res, cnt);
r += 1;
} else break;
}
l += 1;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/08/20/PS/LeetCode/find-the-longest-equal-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.