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 +}