Skip to content

3192. Minimum Operations to Make Binary Array Elements Equal to One II 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int minOperations(vector<int>& nums) {
    int ans = 0;
    int target = 1;

    for (const int num : nums)
      if (num != target) {
        target ^= 1;
        ++ans;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int minOperations(int[] nums) {
    int ans = 0;
    int target = 1;

    for (final int num : nums)
      if (num != target) {
        target ^= 1;
        ++ans;
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def minOperations(self, nums: list[int]) -> int:
    ans = 0
    target = 1

    for num in nums:
      if num != target:
        ans += 1
        target ^= 1

    return ans