Skip to main content
Back to problems
Leetcode
Easy
Arrays
Greedy
Minimum Operations To Make Binary Array Elements Equal To One I

Determine the minimum number of contiguous flip operations needed to turn every element in a binary array into 1.

Acceptance 0%
Problem Statement

Problem

You are given a binary array numsnums containing only 0 and 1.

In one operation, you may choose a starting index ii and flip a length-3 subarray starting at ii, changing each of its elements from 0 to 1 or from 1 to 0.

Return the minimum number of operations needed to make every element in the array equal to 1. If it is impossible, return -1.

Idea

You should reason about the array from left to right and decide when a flip is forced by the current value.

Input Format

  • The input is a binary array nums.
  • Each operation flips exactly three consecutive elements starting at some valid index.

Output Format

Return the minimum number of operations required to make all elements 1, or -1 if it cannot be done.

Constraints

  • 1 <= nums.length
  • nums[i] is either 0 or 1
  • Flips must stay within array bounds
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [0,1,0,1,0,1,0]

Output

3

Explanation

Flip at index 0 -> [1,0,1,1,0,1,0]. Flip at index 1 -> [1,1,0,0,0,1,0]. Flip at index 4 -> [1,1,0,0,1,0,1]. A better sequence exists with 3 flips total, and fewer is not possible.

Example 2

Input

nums = [1,1,1]

Output

0

Explanation

The array is already all ones.

Show 1 more example

Example 3

Input

nums = [0,0]

Output

-1

Explanation

No length-3 flip can be applied, so it is impossible to make all elements equal to 1.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.