Can't come up to the solution on my own... and the logic feels like just worked instead of the correct logic

hey, i understand this solution because it just works here and it feels like since the way the variables are set to come up to the solution but i don’t know how to think like this and especially how can i think of this zero_count to set a logic like this

question : https://leetcode.com/problems/max-consecutive-ones-iii/description/

def max_consecutive_one_with_flip(nums,k):
    left = 0
    zero_count = 0 
    for right in range(len(nums)):
        if nums[right] == 0:
            zero_count += 1

        if zero_count > k:
            if nums[left] == 0:
                zero_count -= 1
            left += 1
        return len(nums) - lefthey, i understand this solution because it just works here and it feels like since the way the variables are set to come up to the solution but i don't know how to think like this and especially how can i think of this zero_count to set a logic like this :

def max_consecutive_one_with_flip(nums,k):
    left = 0
    zero_count = 0 
    for right in range(len(nums)):
        if nums[right] == 0:
            zero_count += 1

        if zero_count > k:
            if nums[left] == 0:
                zero_count -= 1
            left += 1
        return len(nums) - left