- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 52 lines of C++ from the credited upstream file minimum-operations-to-make-array-modulo-alternating-i.cpp.
- The implementation visibly relies on sequence storage.
- 7 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 long long minOperations(vector<int>& nums, int k) {8 const auto& topk = [](const vector<int64_t>& nums, int k) { 9 vector<pair<int64_t, int>> result(k, pair(numeric_limits<int64_t>::max(), numeric_limits<int>::max()));10 for (int i = 0; i < size(nums); ++i) {11 auto x = pair(nums[i], i);12 for (auto& y : result) {13 if (x < y) {14 swap(x, y);15 }16 }17 }18 return result;19 };20 21 const auto& distance = [&](const auto& cnt) {22 const auto& total = accumulate(cbegin(cnt), cend(cnt), 0);23 int c = accumulate(cbegin(cnt) + 1, cbegin(cnt) + (k / 2 + 1), 0);24 vector<int64_t> dist(k);25 for (int i = 0; i < size(cnt); ++i) {26 dist[0] += cnt[i] * min(i, k - i);27 }28 for (int i = 1; i < size(dist); ++i) {29 dist[i] = dist[i - 1] - c + (total - c) - (k % 2 ? cnt[(i + k / 2) % k] : 0);30 c += cnt[(i + k / 2) % k] - cnt[i];31 }32 return dist;33 };34 35 vector<vector<int>> cnt(2, vector<int>(k));36 for (int i = 0; i < size(nums); ++i) {37 ++cnt[i % 2][nums[i] % k];38 }39 vector<vector<int64_t>> dist(2);40 for (int i = 0; i < 2; ++i) {41 dist[i] = distance(cnt[i]);42 }43 vector<vector<pair<int64_t, int>>> top2(2);44 for (int i = 0; i < 2; ++i) {45 top2[i] = topk(dist[i], 2);46 }47 return top2[0][0].second == top2[1][0].second ? min(top2[0][0].first + top2[1][1].first, top2[0][1].first + top2[1][0].first) : top2[0][0].first + top2[1][048].first;49 50 }51};52