Program to find range sum of sorted subarray sums using Python

PythonServer Side ProgrammingProgramming

Suppose we have an array nums with n positive elements. If we compute the sum of all non-empty contiguous subarrays of nums and then sort them in non-decreasing fashion, by creating a new array of n*(n+1)/2 numbers. We have to find the sum of the numbers from index left to index right (1-indexed), inclusive, in the new array. The answer may be very large so return result modulo 10^9 + 7.

So, if the input is like nums = [1,5,2,6] left = 1 right = 5, then the output will be 20 because here all subarray sums are 1, 5, 2, 6, 6, 7, 8, 8, 13, 14, so after sorting, they are [1,2,5,6,6,7,8,8,13,14], the sum of elements from index 1 to 5 is 1+5+2+6+6 = 20.

To solve this, we will follow these steps −

  • m := 10^9 + 7

  • n := size of nums

  • a:= a new list

  • for i in range 0 to n - 1, do

    • for j in range i to n - 1, do

      • if i is same as j, then


        • insert nums[j] at the end of a
      • otherwise,

        • insert ((nums[j] + last element of a) mod m) at the end of a

  • sort the list a

  • sm:= sum of all elements of a[from index left-1 to right])

  • return sm mod m

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(nums, left, right):
   m = 10**9 + 7
   n = len(nums)
   a=[]
   for i in range(n):
      for j in range(i,n):
         if i==j:
            a.append(nums[j])
         else:
            a.append((nums[j]+a[-1])%m)
   a.sort()
   sm=sum(a[left-1:right])
   return sm % m
nums = [1,5,2,6]
left = 1
right = 5
print(solve(nums, left, right))

Input

[1,5,2,6], 1, 5

Output

20
raja
Updated on 29-May-2021 12:58:22

Advertisements