LeetCode/go/find-score-of-an-array-after-marking-all-elements.go

40 lines
858 B
Go
Raw Permalink Normal View History

package main
import (
"cmp"
pq "github.com/emirpasic/gods/v2/queues/priorityqueue"
)
type Candidate struct {
value int
index int
}
func smallestFirst(l, r Candidate) int {
return cmp.Or(cmp.Compare(l.value, r.value), cmp.Compare(l.index, r.index))
}
func findScore(nums []int) int64 {
candidates := pq.NewWith(smallestFirst)
for i, num := range nums {
candidates.Enqueue(Candidate{value: num, index: i})
}
score, marked := int64(0), make([]bool, len(nums))
for nextCandidate, ok := candidates.Dequeue(); ok; nextCandidate, ok = candidates.Dequeue() {
if marked[nextCandidate.index] {
continue
}
score += int64(nextCandidate.value)
for _, index := range []int{nextCandidate.index - 1, nextCandidate.index, nextCandidate.index + 1} {
if index >= 0 && index < len(marked) {
marked[index] = true
}
}
}
return score
}