go: add «135. Candy»

URL:	https://leetcode.com/problems/candy/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-01-05 21:58:11 +01:00
parent 9bcb76c340
commit 7166a19f10
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

37
go/candy.go Normal file
View file

@ -0,0 +1,37 @@
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
}