diff --git a/go/find-score-of-an-array-after-marking-all-elements.go b/go/find-score-of-an-array-after-marking-all-elements.go new file mode 100644 index 0000000..15d1322 --- /dev/null +++ b/go/find-score-of-an-array-after-marking-all-elements.go @@ -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 +}