Search This Blog

Solution to TCS Pan India Hiring Drive - Python [ Coding Round ]

 Question:

Minimum Absolute Difference (100 Marks)

You have an array of size N. Calculate the sum of minimum absolute differences for all the elements of the given array.


Note: N will always be an even number.

Input Format

The first line contains a single integer N, the size of the array.

The second line contains N integers, the elements of the array.

Constraints

2 <= N <= 103

0 <= Ai <= 103

Output Format

Print the sum of minimum absolute differences.


Note: There is a new line at the end of the output.

Sample TestCase 1

Input

4

5 10 10 15

Output

10

Explanation

Minimum absolute difference for element 1 = 5


Minimum absolute difference for element 2 and 3 = 0

Minimum absolute difference for element 4 = 5


Sum of minimum absolute differences = 5 + 0 + 0 + 5 = 10

Sample TestCase 2

Input

6

1 3 3 7 4 7

Output

3


Solution:

def main():

    def absDifferenceMinSum(anum):
        sum = 0
        a.sort()
        
        sum += abs(a[0] - a[1])
        sum += abs(a[num - 1] - a[num - 2])
        for i in range(1num - 1):
            sum += min(abs(a[i] - a[i - 1]),
                    abs(a[i] - a[i + 1]))
        return sum


    size_of_list = int(input(""))
    a = list(map(intinput().split()))
    num = len(a)
    print(absDifferenceMinSum(anum))



main()

No comments:

Post a Comment