- 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
- 44 lines of C++ from the credited upstream file minimum-operations-to-achieve-at-least-k-peaks.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 2 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 int minOperations(vector<int>& nums, int k) {8 if (2 * k > size(nums)) {9 return -1;10 }11 if (!k) {12 return 0;13 }14 vector<bool> lookup(size(nums));15 vector<int> left(size(nums)), right(size(nums)), cost(size(nums));16 vector<pair<int, int>> pairs(size(nums));17 for (int i = 0; i < size(nums); ++i) {18 left[i] = (size(nums) + (i - 1)) % size(nums);19 right[i] = (size(nums) + (i + 1)) % size(nums);20 cost[i] = max((max(nums[left[i]], nums[right[i]]) + 1) - nums[i], 0);21 pairs[i] = pair(cost[i], i);22 }23 priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> min_heap(cbegin(pairs), cend(pairs));24 int result = 0;25 while (!empty(min_heap)) {26 const auto [c, i] = min_heap.top(); min_heap.pop();27 if (lookup[i]) {28 continue;29 }30 result += c;31 if (!--k) {32 break;33 }34 cost[i] = cost[left[i]] + cost[right[i]] - cost[i];35 min_heap.emplace(cost[i], i);36 lookup[left[i]] = lookup[right[i]] = true;37 left[i] = left[left[i]];38 right[i] = right[right[i]];39 right[left[i]] = left[right[i]] = i;40 }41 return result;42 }43};44