Max Consecutive Ones III LeetCode Solution

🚀 LeetCode Problem Solved: Max Consecutive Ones III (Sliding Window Technique) Day 16 of #75DaysofLeetCode Today I solved LeetCode 1004 – Max Consecutive Ones III, a great problem to practice the Sliding Window / Two Pointer technique. 🔹 Problem: Given a binary array and an integer k, we can flip at most k zeros to ones. The goal is to find the maximum number of consecutive 1’s in the array after performing at most k flips. 💡 Key Idea: Instead of checking every possible subarray, we maintain a sliding window and allow at most k zeros inside the window. If the number of zeros exceeds k, we shrink the window from the left until the condition becomes valid again. ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) 💻 Java Implementation: class Solution { public int longestOnes(int[] nums, int k) { int left = 0; int zeroCount = 0; int maxLen = 0; for (int right = 0; right < nums.length; right++) { if (nums[right] == 0) { zeroCount++; } while (zeroCount > k) { if (nums[left] == 0) { zeroCount--; } left++; } maxLen = Math.max(maxLen, right - left + 1); } return maxLen; } } 📚 This problem strengthened my understanding of efficient window management in arrays, which is a common pattern in coding interviews. #LeetCode #Java #SlidingWindow #DSA #ProblemSolving #CodingJourney #SoftwareDevelopment

  • text

To view or add a comment, sign in

Explore content categories