题目:
leetcode.cn/problems/fi…
算法:
方法一:前缀和
func goodDaysToRobBank(security []int, time int) []int {
// 初始化数组g, g[i] = 0, security[i-1]=security[i]
// g[i] = 1, security[i-1] < security[i]
// g[i] = -1, security[i-1] > security[i]
// 如果i天前连续time天警卫数非递增,则有g[i] - t[i - time - 1] == time
ans := make([]int, 0)
n := len(security)
g := make([]int, n)
for i := 1; i < n; i ++ {
if security[i] > security[i - 1] {
g[i] = 1
} else if security[i] < security[i - 1] {
g[i] = -1
}
}
// a[i + 1], b[i + 1]分别代表security[i]之前大于等于security[i],之前小于等于security[i]的数量
a, b := make([]int, n + 1), make([]int, n + 1)
for i := range g {
if g[i] == 0 {
a[i + 1] = a[i]
b[i + 1] = b[i]
} else if g[i] == 1 {
a[i + 1] = a[i] + 1
b[i + 1] = b[i]
} else {
a[i + 1] = a[i]
b[i + 1] = b[i] + 1
}
}
for i := time; i + time < n; i ++ {
descAndEqCount := a[i + 1] - a[i + 1 - time ]
ascAndEqCount := b[i + time + 1] - b[i + 1]
if descAndEqCount == 0 && ascAndEqCount == 0 {
ans = append(ans, i)
}
}
return ans
}