Leetcode: 1508 Range Sum of Sorted Subarray Sums

Description

You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.

Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7.

Example

Input: nums = [1,2,3,4], n = 4, left = 1, right = 5
Output: 13 
Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.

分析

  • 正确的思路
1. 采用二分
以  n=4, nums = [1,2,3,4] 为例, prefixSum = [1, 3, 6, 10]

step1
       猜一个数 M
        for i in range(4):
            二分查找出 prefixSum 小于等于 M + nums[i] - nums[0] 个数
step2
    如小于等于 M 的个数大于 rightnum 或 leftnum, 则缩小 M 的值  。 否则增大 M 值 (常规的 二分更新法则)
    如小小于等于 M 的个数等于 rightnum 或者。leftnum。则进入到第三步

step3
   total  = 0
        for i in range(4):
          curTotal = 0
          for j in range(i, 4):
             curTotal += nums[j]
             if curTotal > M:
                  break 
            total += curTotal


2. 采用最小堆, 代码如下
import heapq
class Solution(object):
    def rangeSum(self, nums, n, left, right):
        """
        :type nums: List[int]
        :type n: int
        :type left: int
        :type right: int
        :rtype: int
        """
        q, total_sum = [], 0
        
        for i in range(n):
            heapq.heappush(q, [nums[i], i])
        
        for i in range(1, right+1):
            v, idx = heapq.heappop(q)
          
            if i >= left:
                total_sum += v
            if n-1 > idx:
                idx += 1
                heapq.heappush(q, [v+nums[idx], idx])
        return total_sum % 1000000007

总结

Runtime: 560 ms, faster than 48.15% of Python online submissions for Range Sum of Sorted Subarray Sums.
Memory Usage: 29.2 MB, less than 88.89% of Python online submissions for Range Sum of Sorted Subarray Sums.
上一篇:leetcode1712. 将数组分成三个子数组的方案数


下一篇:【AT4434】[ARC103D] Distance Sums(构造)