- 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

Suppose we have a list of sorted numbers called nums, we have to find the sum of the absolute differences between every pair of numbers in the given list. Here we will consider (i, j) and (j, i) are different pairs. If the answer is very large, mod the result by 10^9+7.

So, if the input is like nums = [2, 4, 8], then the output will be 24, as |2 - 4| + |2 - 8| + |4 - 2| + |4 - 8| + |8 - 2| + |8 - 4|.

To solve this, we will follow these steps −

m = 10^9 + 7

total := 0

for i in range 0 to size of nums, do

total := total +(i*nums[i] - (size of nums - 1 - i) *nums[i]) mod m

return (2*total) mod m

Let us see the following implementation to get better understanding −

class Solution: def solve(self, nums): m = 10**9 + 7 total = 0 for i in range(len(nums)): total += (i*nums[i] - (len(nums) - 1 - i)*nums[i]) % m return (2*total) % m ob = Solution() nums = [2, 4, 8] print(ob.solve(nums))

[2, 4, 8]

24

- Related Questions & Answers
- Python program to find sum of absolute difference between all pairs in a list
- Program to find the number of unique integers in a sorted list in Python
- Python program to find Cumulative sum of a list
- Python Program for Find the closest pair from two sorted arrays
- Python program to find sum of elements in list
- Program to find sum of minimum trees from the list of leaves in python
- Array element with minimum sum of absolute differences?
- Python Program to Find the Total Sum of a Nested List Using Recursion
- Find the sum of array in Python Program
- Python Program to find the sum of array
- Find sum of elements in list in Python program
- XOR of Sum of every possible pair of an array in C++
- Program to find range sum of sorted subarray sums using Python
- Program to find sum of the sum of all contiguous sublists in Python
- Array element with minimum sum of absolute differences in C++?

Advertisements