Skip to main content
Back to problems
#487
Medium Algorithms

Max consecutive ones ii

Array Dynamic Programming Sliding Window
52.0% acceptance
Mar 31, 2026
1607
27
Given a binary array nums, return the maximum number of consecutive 1's in the array if you can flip at most one 0.

Solution

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