

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find range sum of sorted subarray sums using Python
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
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
- Related Questions & Answers
- Program to find sum of the 2 power sum of all subarray sums of a given array in Python
- Program to find maximum ascending subarray sum using Python
- Program to find maximum absolute sum of any subarray in Python
- Program to find shortest subarray to be removed to make array sorted in Python
- C++ Program to Find the maximum subarray sum using Binary Search approach
- Program to find the maximum sum of the subarray modulo by m in Python
- Program to find sum of absolute differences in a sorted array in Python
- Maximum sum subarray having sum less than or equal to given sums in C++
- Program to find out the sum of the maximum subarray after a operation in Python
- Program to find longest subarray of 1s after deleting one element using Python
- Program to find maximum product of contiguous subarray in Python
- Maximum Subarray Sum in a given Range in C++
- Program to find maximum sum of two sets where sums are equal in C++
- Using Kadane’s algorithm to find maximum sum of subarray in JavaScript
- Find missing numbers in a sorted list range in Python