<p>You are given the array <code>nums</code> consisting of <code>n</code> 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 <code>n * (n + 1) / 2</code> numbers.</p>

<p><em>Return the sum of the numbers from index </em><code>left</code><em> to index </em><code>right</code> (<strong>indexed from 1</strong>)<em>, inclusive, in the new array. </em>Since the answer can be a huge number return it modulo <code>10<sup>9</sup> + 7</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3,4], n = 4, left = 1, right = 5
<strong>Output:</strong> 13 
<strong>Explanation:</strong> 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. 
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3,4], n = 4, left = 3, right = 4
<strong>Output:</strong> 6
<strong>Explanation:</strong> The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3,4], n = 4, left = 1, right = 10
<strong>Output:</strong> 50
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == nums.length</code></li>
	<li><code>1 &lt;= nums.length &lt;= 1000</code></li>
	<li><code>1 &lt;= nums[i] &lt;= 100</code></li>
	<li><code>1 &lt;= left &lt;= right &lt;= n * (n + 1) / 2</code></li>
</ul>

class Solution:

    def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:
        if n < 10:
            return self.rangeSumPython(nums, n, left, right)
        if n < 30:
            return self.rangeSumNumpy(nums, n, left, right)
        return self.rangeSumBinary(nums, n, left, right)

    def rangeSumBinary(self, nums: List[int], n: int, left: int, right: int) -> int:
        """From Editoral - Approach 3."""
        min_sum = min(nums)
        max_sum = sum(nums)

        def count_and_sum(nums, n, target):
            """Helper function to count subarrays with sum <= target and their total sum."""
            count = 0
            current_sum = 0
            total_sum = 0
            window_sum = 0
            i = 0
            for j in range(n):
                current_sum += nums[j]
                window_sum += nums[j] * (j - i + 1)
                while current_sum > target:
                    window_sum -= current_sum
                    current_sum -= nums[i]
                    i += 1
                count += j - i + 1
                total_sum += window_sum
            return count, total_sum

        def sum_of_first_k(nums, n, k, min_sum=min_sum, max_sum=max_sum):
            """Helper function to find the sum of the first k smallest subarray sums."""
            left = min_sum
            right = max_sum
            while left <= right:
                mid = (left + right) // 2
                if count_and_sum(nums, n, mid)[0] >= k:
                    right = mid - 1
                else:
                    left = mid + 1
            count, total_sum = count_and_sum(nums, n, left)
            # There can be more subarrays with the same sum of left.
            return total_sum - left * (count - k)

        result = sum_of_first_k(nums, n, right) - sum_of_first_k(nums, n, left - 1)
        return result % 1000000007

    def rangeSumHeap(self, nums: List[int], n: int, left: int, right: int) -> int:
        """From Editoral - Approach 2."""
        import heapq
        pq = [(nums[i], i) for i in range(n)]
        heapq.heapify(pq)

        ans = 0
        for i in range(1, right + 1):
            p = heapq.heappop(pq)
            # If the current index is greater than or equal to left, add the value to the answer.
            if i >= left:
                ans += p[0]
            # If index is less than the last index, increment it and add its value to the first pair value.
            if p[1] < n - 1:
                p = (p[0] + nums[p[1] + 1], p[1] + 1)
                heapq.heappush(pq, p)
        return ans % 1000000007

    def rangeSumPython(self, nums: List[int], n: int, left: int, right: int) -> int:
        from itertools import accumulate
        sums = [None] * int(n * (n + 1) / 2)
        # TODO: Interrupt the sum before it reaches "right".
        #  In other words, only calculate the combinations needed.
        counter = 0
        for i in range(len(nums)):
            sums[counter: counter + n - i] = accumulate(nums[i: n])
            counter = counter + n - i
        sums.sort()
        return sum(sums[left-1: right]) % 1000000007

    def rangeSumNumpy(self, nums: List[int], n: int, left: int, right: int) -> int:
        import numpy as np
        # We cannot pre-sort the input, because the requirement is "contiguous subarray"!
        # Test case: [9,1,1,7,1], n=5, left=5, right=5. Expected=7, output=2!
        # Pre-sorted: [ 1  1  1  2  2  3  7  8  9  9 10 16 17 18 19]
        # Expected  : [ 1  1  1  2  7  8  8  9  9  9 10 10 11 18 19]
        nums = np.array(nums, dtype=np.uint8)  # Max possible value is 100.
        sums = np.empty(shape=int(n * (n + 1) / 2), dtype=np.uint32)  # Max possible value is 100 * 1000 = 100,000.
        counter = 0
        for i in range(n):
            sums[counter: counter + n - i] = np.cumsum(nums[i: n], dtype=np.uint32)
            # sums[counter: counter + n - i].sort()  # Partial sort doesn't help.
            counter = counter + n - i
        # sums.sort(kind="mergesort")
        sums.sort()
        # TODO: Modulo should have been applied within the reduction step, but somehow this works. So anyways...
        return sums[left-1: right].sum() % 1000000007

27657