- 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
- 49 lines of C++ from the credited upstream file 3048.cpp.
- The implementation visibly relies on sequence storage.
- 3 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.
1class Solution {2 public:3 int earliestSecondToMarkIndices(vector<int>& nums,4 vector<int>& changeIndices) {5 int l = 0;6 int r = changeIndices.size() + 1;7 8 while (l < r) {9 const int m = (l + r) / 2;10 if (canMark(nums, changeIndices, m))11 r = m;12 else13 l = m + 1;14 }15 16 return l <= changeIndices.size() ? l : -1;17 }18 19 private:20 21 bool canMark(const vector<int>& nums, const vector<int>& changeIndices,22 int second) {23 int numMarked = 0;24 int decrement = 0;25 26 vector<int> indexToLastSecond(nums.size(), -1);27 28 for (int i = 0; i < second; ++i)29 indexToLastSecond[changeIndices[i] - 1] = i;30 31 for (int i = 0; i < second; ++i) {32 const int index = changeIndices[i] - 1; 33 if (i == indexToLastSecond[index]) {34 35 36 if (nums[index] > decrement)37 38 return false;39 decrement -= nums[index];40 ++numMarked;41 } else {42 ++decrement;43 }44 }45 46 return numMarked == nums.size();47 }48};49