- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 the sum of the absolute differences of every pair in a sorted list in Python
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 −
Example
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))
Input
[2, 4, 8]
Output
24
- Related Articles
- Program to find sum of absolute differences in a sorted array in Python
- 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
- Program to find maximum absolute sum of any subarray in Python
- Program to find minimum absolute sum difference in Python
- Python program to find sum of elements in list
- Program to find sum of the minimums of each sublist from a list in Python
- Python program to find Cumulative sum of a list
- Python Program for Find the closest pair from two sorted arrays
- Program to find sum of minimum trees from the list of leaves in python
- Find sum of elements in list in Python program
- Program to find range sum of sorted subarray sums using Python
- Python Program to Find the Total Sum of a Nested List Using Recursion
- Program to find squared elements list in sorted order in Python
- Program to find largest distance pair from two list of numbers in Python

Advertisements