[LeetCode] Minimum Seconds to Equalize a Circular Array

2808. Minimum Seconds to Equalize a Circular Array

You are given a 0-indexed array nums containing n integers.

At each second, you perform the following operation on the array:

  • For every index i in the range [0, n - 1], replace nums[i] with either nums[i], nums[(i - 1 + n) % n], or nums[(i + 1) % n].

Note that all the elements get replaced simultaneously.

Return the minimum number of seconds needed to make all elements in the array nums equal.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int minimumSeconds(vector<int>& nums) {
unordered_map<int, vector<int>> mp;
int res = INT_MAX;
for(int i = 0; i < nums.size(); i++) mp[nums[i]].push_back(i);
for(auto& [k,vec] : mp) {
int ma = 0;
for(int i = 0; i < vec.size(); i++) {
if(i + 1 == vec.size()) {
ma = max(ma, vec[0] + (int)nums.size() - 1 - vec[i]);
} else ma = max(ma, vec[i+1] - vec[i] - 1);
}
res = min(res, (ma + 1) / 2);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/08/06/PS/LeetCode/minimum-seconds-to-equalize-a-circular-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.