Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,28 +1,41 @@
# [3191.Minimum Operations to Make Binary Array Elements Equal to One I][title]

> [!WARNING|style:flat]
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)

## Description
You are given a `binary array` `nums`.

You can do the following operation on the array **any** number of times (possibly zero):

- Choose **any 3 consecutive** elements from the array and **flip all** of them.

**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. If it is impossible, return -1.

**Example 1:**

```
Input: a = "11", b = "1"
Output: "100"
```
Input: nums = [0,1,1,1,0,0]

## 题意
> ...
Output: 3

## 题解
Explanation:
We can do the following operations:

### 思路1
> ...
Minimum Operations to Make Binary Array Elements Equal to One I
```go
Choose the elements at indices 0, 1 and 2. The resulting array is nums = [1,0,0,1,0,0].
Choose the elements at indices 1, 2 and 3. The resulting array is nums = [1,1,1,0,0,0].
Choose the elements at indices 3, 4 and 5. The resulting array is nums = [1,1,1,1,1,1].
```

**Example 2:**

```
Input: nums = [0,1,1,1]

Output: -1

Explanation:
It is impossible to make all elements equal to 1.
```

## 结语

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
package Solution

func Solution(x bool) bool {
return x
func Solution(nums []int) int {
ans := 0
index := 0
l := len(nums)
for ; index < l; index++ {
if nums[index] == 1 {
continue
}
if index >= l-2 {
return -1
}
nums[index] = 1 - nums[index]
nums[index+1] = 1 - nums[index+1]
nums[index+2] = 1 - nums[index+2]
ans++
}
return ans
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs bool
expect bool
inputs []int
expect int
}{
{"TestCase", true, true},
{"TestCase", true, true},
{"TestCase", false, false},
{"TestCase1", []int{0, 1, 1, 1, 0, 0}, 3},
{"TestCase2", []int{0, 1, 1, 1}, -1},
}

// 开始测试
Expand All @@ -30,10 +29,10 @@ func TestSolution(t *testing.T) {
}
}

// 压力测试
// 压力测试
func BenchmarkSolution(b *testing.B) {
}

// 使用案列
// 使用案列
func ExampleSolution() {
}
Loading