go: add «2593. Find Score of an Array After Marking All Elements»
URL: https://leetcode.com/problems/find-score-of-an-array-after-marking-all-elements/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
da959699dd
commit
c15de5ee79
1 changed files with 39 additions and 0 deletions
39
go/find-score-of-an-array-after-marking-all-elements.go
Normal file
39
go/find-score-of-an-array-after-marking-all-elements.go
Normal file
|
@ -0,0 +1,39 @@
|
||||||
|
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
|
||||||
|
}
|
Loading…
Reference in a new issue