From 0e4bb92726111a9b18962e454d46a85ebde9cef8 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 4 Aug 2024 14:36:18 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB1508.=20Range=20Sum=20of=20So?= =?UTF-8?q?rted=20Subarray=20Sums=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- go/range-sum-of-sorted-subarray-sums.go | 43 +++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 go/range-sum-of-sorted-subarray-sums.go diff --git a/go/range-sum-of-sorted-subarray-sums.go b/go/range-sum-of-sorted-subarray-sums.go new file mode 100644 index 0000000..6fed418 --- /dev/null +++ b/go/range-sum-of-sorted-subarray-sums.go @@ -0,0 +1,43 @@ +package main + +import ( + "cmp" + + pq "github.com/emirpasic/gods/v2/queues/priorityqueue" +) + +const MOD int = 1_000_000_007 + +type Sum struct { + index int + sum int +} + +func cmpSum(a, b Sum) int { + return cmp.Compare(a.sum, b.sum) +} + +func rangeSum(nums []int, n int, left int, right int) int { + q := pq.NewWith[Sum](cmpSum) + + for i, num := range nums { + q.Enqueue(Sum{index: i, sum: num}) + } + + total := 0 + for i := 1; i <= right; i++ { + s, _ := q.Dequeue() + + if i >= left { + total = (total + s.sum) % MOD + } + + if s.index < n-1 { + s.index++ + s.sum += nums[s.index] + q.Enqueue(s) + } + } + + return total +}