[LeetCode] Minimum Operations to Make Array Modulo Alternating I

3937. Minimum Operations to Make Array Modulo Alternating I

You are given an integer array nums and an integer k.

In one operation, you can increase or decrease any element of nums by 1.

An array is called modulo alternating if there exist two distinct integers x and y (0 <= x, y < k) such that:

  • For every even index i, nums[i] % k == x
  • For every odd index i, nums[i] % k == y

Return the minimum number of operations required to make nums modulo alternating.

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
26
27
28
29
30
31
32
33

class Solution {
vector<pair<long long,long long>> helper(vector<int>& A, int k) {
unordered_set<int> us;
unordered_map<int,int> freq;
for(auto& n : A) us.insert(n%k), us.insert((n - 1 + k) % k), us.insert((n + 1) % k), freq[n%k]++;
vector<pair<long long,long long>> res{{INT_MAX,INT_MAX},{INT_MAX,INT_MAX}};

for(auto& u : us) {
int cost = 0;
for(auto& [K,v] : freq) {
int c = abs(K-u);
c = min(c, (k - c) % k);
cost += v * c;
if(cost >= res.back().first) break;
}
res.push_back({cost,u});
sort(begin(res), end(res));
res.pop_back();
}
return res;
}
public:
int minOperations(vector<int>& nums, int k) {
long long res = INT_MAX, n = nums.size();
if(n == 1) return 0;
vector<int> vals[2];
for(int i = 0; i < nums.size(); i++) vals[i&1].push_back(nums[i]%k);
auto a = helper(vals[0], k), b = helper(vals[1], k);
for(auto& [k1,v1] : a) for(auto& [k2,v2] : b) if(v1 != v2) res = min(res, k1 + k2);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-operations-to-make-array-modulo-alternating-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.