go: add «1508. Range Sum of Sorted Subarray Sums»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
ef9c473c21
commit
0e4bb92726
1 changed files with 43 additions and 0 deletions
43
go/range-sum-of-sorted-subarray-sums.go
Normal file
43
go/range-sum-of-sorted-subarray-sums.go
Normal 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
|
||||
}
|
Loading…
Reference in a new issue