Skip to main content
Back to problems
#1004
Medium Algorithms

Max consecutive ones iii

Array Binary Search Sliding Window Prefix Sum
67.3% acceptance
Feb 25, 2026
10354
184
Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn longest_ones(nums: Vec<i32>, k: i32) -> i32 {
    let mut zeros = 0;
    let mut left = 0;
    let mut ans = 0;
    for right in 0..nums.len() {
      if nums[right] == 0 { zeros += 1; }
      while zeros > k { if nums[left] == 0 { zeros -= 1; } left += 1; }
      ans = ans.max((right - left + 1) as i32);
    }
    ans
  }
}