Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 1004 · Variable Window – Longest

Max Consecutive Ones III

LeetCode 1004 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Longest window with ≤ k zeros.

ಮಧ್ಯಮArrayBinary SearchSliding WindowPrefix Sum
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 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.