LeetCode/go/candy.go
Matej Focko 7166a19f10
go: add «135. Candy»
URL:	https://leetcode.com/problems/candy/
Signed-off-by: Matej Focko <me@mfocko.xyz>
2025-01-05 21:58:11 +01:00

37 lines
588 B
Go

package main
func candy(ratings []int) int {
n := len(ratings)
given, i := n, 1
for i < n {
if ratings[i-1] == ratings[i] {
// same rating ⇒ no need for adjustments
i++
continue
}
// increasing rating
localMax := 0
for ; i < n && ratings[i-1] < ratings[i]; i++ {
localMax += 1
given += localMax
}
if i >= n {
return given
}
// decreasing rating
localMin := 0
for ; i < n && ratings[i-1] > ratings[i]; i++ {
localMin += 1
given += localMin
}
// count the extrema only once
given -= min(localMin, localMax)
}
return given
}