💡 Sliding Window: A variable-sized window that slides forward in the same direction (fixed at the right end, sliding at the left end). It can be imagined as a queue, with one end pushing and the other end popping elements.
Idea:
- Use the "left-right pointer" technique in the sequence, initialize
left = right = 0
, and call the index closed interval [left, right] a window.
- First, continuously increase the right pointer to expand the window until the sequence in the window meets the requirements.
- At this point, stop increasing the right pointer and instead continuously increase the left pointer to shrink the window until the sequence in the window no longer meets the requirements. At the same time, update the result before each increase in the left pointer.
- Repeat steps 2 and 3 until the right reaches the end of the sequence.
Step 2 is equivalent to finding a feasible solution
, and step 3 is optimizing the feasible solution
, finally finding the optimal solution
. The left and right pointers advance alternately, the window size increases and decreases, and the window slides to the right.