๐Ÿ“ฆ jtr109 / go-playground

๐Ÿ“„ lib.go ยท 22 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22package flipstringtomonotoneincreasing

import "strings"

func minFlipsMonoIncr(s string) int {
	flipCount := []int{strings.Count(s, "0")} // flip all into 1
	for _, c := range s {
		if c == '0' {
			flipCount = append(flipCount, flipCount[len(flipCount)-1]-1)
		} else {
			flipCount = append(flipCount, flipCount[len(flipCount)-1]+1)
		}
	}
	minCount := flipCount[0]
	for _, c := range flipCount {
		if c < minCount {
			minCount = c
		}
	}
	return minCount
}