From c15de5ee79e504be45579486e35e75ae475eee26 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 14 Dec 2024 00:05:35 +0100 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB2593.=20Find=20Score=20of=20a?= =?UTF-8?q?n=20Array=20After=20Marking=20All=20Elements=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/find-score-of-an-array-after-marking-all-elements/ Signed-off-by: Matej Focko --- ...-of-an-array-after-marking-all-elements.go | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 go/find-score-of-an-array-after-marking-all-elements.go 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 +}