Skip to main content
Back to problems
#3192
Medium Algorithms

Minimum operations to make binary array elements equal to one ii

Array Dynamic Programming Greedy
65.0% acceptance
Feb 24, 2026
152
9
You are given a binary array nums. You can do the following operation on the array any number of times (possibly zero): Choose any index i from the array and flip all the elements from index i to the end of the array. Flipping an element means changing its value from 0 to 1, and from 1 to 0. Return the minimum number of operations required to make all elements in nums equal to 1.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_operations(nums: Vec<i32>) -> i32 {
    // Each operation flips from index i to end.
    // Greedy: scan left to right; whenever current value (accounting for flips) is 0, we must flip here.
    let mut ops = 0;
    let mut flipped = 0; // current parity: 0 = not flipped, 1 = flipped
    for &v in &nums {
      let actual = v ^ flipped;
      if actual == 0 {
        ops += 1;
        flipped ^= 1;
      }
    }
    ops
  }
}