- 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 sum of absolute differences in a sorted array in Python

Suppose we have an array nums and that is sorted in non-decreasing order. We have to make an array called result with the same length as nums such that result[i] is the summation of absolute differences between nums[i] and all the other elements in the array.

So, if the input is like nums = [5,7,12], then the output will be [9, 7, 12] because

- |5-5| + |5-7| + |5-12| = 0+2+7 = 9
- |7-5| + |7-7| + |7-12| = 2+0+5 = 7
- |5-12| + |7-12| + |12-12| = 7+5+0 = 12

To solve this, we will follow these steps −

- res := a new list
- s:= 0
- n := size of nums
- for i in range 1 to n - 1, do
- s := s + nums[i] - nums[0]

- insert s at the end of res
- for i in range 1 to n - 1, do
- diff := nums[i] - nums[i-1]
- s := s + diff*i
- s := s - diff *(n-i)

- insert s at the end of res
- return res

## Example

Let us see the following implementation to get better understanding −

def solve(nums): res = [] s=0 n = len(nums) for i in range(1,n): s+=nums[i]-nums[0] res.append(s) for i in range(1,n): diff = nums[i]-nums[i-1] s += diff*i s -= diff *(n-i) res.append(s) return res nums = [5,7,12] print(solve(nums))

## Input

[5,7,12]

## Output

[9, 7, 12]

- Related Articles
- Program to find the sum of the absolute differences of every pair in a sorted list in Python
- Program to find minimum absolute sum difference in Python
- Array element with minimum sum of absolute differences?
- Array element with minimum sum of absolute differences in C++?
- Program to find maximum absolute sum of any subarray in Python
- Absolute distinct count in a sorted array?
- Python program to find sum of absolute difference between all pairs in a list
- Absolute distinct count in a sorted array in C++?
- Program to find max chunks to make array sorted in Python
- Program to find range sum of sorted subarray sums using Python
- Find the sum of array in Python Program
- Program to find running sum of 1d array in Python
- Python Program to find the sum of array
- Program to find shortest subarray to be removed to make array sorted in Python
- Absolute sum of array elements - JavaScript

Advertisements