Re: [闲聊] 每日leetcode

楼主: dont   2024-08-04 12:12:27
1508. Range Sum of Sorted Subarray Sums
## 思路
建heap 存range_sum 跟 idx
每次pop出来的值再加上nums[idx+1]丢回去heap
然后加总left~right次pop的range sum
## Complexity
Time: O(max(N, right) log N) = O(N^2 logN)
Space: O(N)
```python
class Solution:
def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:
MOD = 1_000_000_007
# O(N)
pq = [(num, idx) for idx, num in enumerate(nums)] # (num, idx)
heapq.heapify(pq)
# O(max(N, right) log N)
ans = 0
for i in range(1, right+1):
num, idx = heapq.heappop(pq)
if i >= left:
ans = (ans + num) % MOD
if idx + 1 < n:
heapq.heappush(pq, (num + nums[idx+1], idx+1))
return ans
```
作者: sustainer123 (caster)   2024-08-04 12:16:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com