go: add «1508. Range Sum of Sorted Subarray Sums»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-04 14:36:18 +02:00
parent ef9c473c21
commit 0e4bb92726
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

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