- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 65 lines of C++ from the credited upstream file minimum-operations-to-make-array-parity-alternating.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 vector<int> makeParityAlternating(vector<int>& nums) {8 static const int POS_INF = numeric_limits<int>::max();9 static const int NEG_INF = numeric_limits<int>::min();10 11 const auto& count = [&](int target) {12 int cnt = 0;13 int mn = POS_INF, mx = NEG_INF;14 for (int i = 0; i < size(nums); ++i) {15 if ((nums[i] & 1) == ((i & 1) ^ target)) {16 mn = min(mn, nums[i]);17 mx = max(mx, nums[i]);18 } else {19 ++cnt;20 mn = min(mn, nums[i] + 1);21 mx = max(mx, nums[i] - 1);22 }23 }24 return vector<int>{cnt, size(nums) == 1 ? 0 : (ranges::max(nums) == ranges::min(nums) ? 1 : mx - mn)};25 };26 27 return min(count(0), count(1));28 }29};30 31323334class Solution2 {35public:36 vector<int> makeParityAlternating(vector<int>& nums) {37 static const int POS_INF = numeric_limits<int>::max();38 static const int NEG_INF = numeric_limits<int>::min();39 40 const auto& count = [&](int target) {41 int cnt = 0;42 int mn = ranges::min(nums), mx = ranges::max(nums);43 int mn2 = POS_INF, mx2 = NEG_INF;44 for (int i = 0; i < size(nums); ++i) {45 if ((nums[i] & 1) == ((i & 1) ^ target)) {46 mn2 = min(mn2, nums[i]);47 mx2 = max(mx2, nums[i]);48 } else {49 ++cnt;50 if (nums[i] == mn) {51 mn2 = min(mn2, nums[i] + 1);52 mx2 = max(mx2, nums[i] + 1);53 } else if (nums[i] == mx) {54 mn2 = min(mn2, nums[i] - 1);55 mx2 = max(mx2, nums[i] - 1);56 }57 }58 }59 return vector<int>{cnt, mx2 - mn2};60 };61 62 return min(count(0), count(1));63 }64};65