Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 1004 · Variable Window – Longest

Max Consecutive Ones III

LeetCode 1004 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Longest window with ≤ k zeros.

मध्यमArrayBinary SearchSliding WindowPrefix Sum

मी Max Consecutive Ones III (LeetCode 1004) असा सोडवला — Variable Window – Longest पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.

खालील विवरण इंग्रजीत आहे.

Intuition

Flipping at most k zeros means: find the longest window containing at most k zeros. Grow the window to the right; when it holds too many zeros, slide the left edge.

Approach

  1. 1

    Count zeros in the window.

  2. 2

    If zeros > k, move l right (decrement if a zero leaves).

  3. 3

    Track the window length.

मी कसा सोडवला

Sliding windowPythonO(n) time · O(1) space
class Solution:
    def longestOnes(self, nums: List[int], k: int) -> int:
        #sliding window and two pointer
        #count the number of zeroes in the current window
        #if it exceeds, shrink from left, take care of count of 0 - left most position
        l=0
        r=0
        cnt_zeros = 0
        max_length = float("-inf")
        while r<len(nums):
            cur = nums[r]
            if cur==0:
               cnt_zeros+=1
            if cnt_zeros>k:
                if nums[l]==0:
                    cnt_zeros-=1
                l+=1
            max_length=max(max_length,r-l+1)
            r+=1
        return max_length
स्टेप-थ्रू लोड होत आहे…

Max Consecutive Ones III — वारंवार विचारले जाणारे प्रश्न

Max Consecutive Ones III मागील intuition काय आहे?

Flipping at most k zeros means: find the longest window containing at most k zeros. Grow the window to the right; when it holds too many zeros, slide the left edge.

Max Consecutive Ones III (LeetCode 1004) कसा सोडवावा?

1. Count zeros in the window. 2. If zeros > k, move l right (decrement if a zero leaves). 3. Track the window length.

Max Consecutive Ones III ची time आणि space complexity किती आहे?

Time: O(n). Space: O(1). (Accepted approach: Sliding window.)

Max Consecutive Ones III मध्ये सामान्य चुका कोणत्या?

The window never shrinks, only slides — that's fine because we only need the max length.