go: add «135. Candy»
URL: https://leetcode.com/problems/candy/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
9bcb76c340
commit
7166a19f10
1 changed files with 37 additions and 0 deletions
37
go/candy.go
Normal file
37
go/candy.go
Normal 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
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue