from sortedcontainers import SortedList window = SortedList() window.remove(nums[i - 1 - k]) window.add(nums[i])