CHAAT2 - Editorial

PROBLEM LINK:

Contest

Author: Dharsan R
Tester: Dharsan R
Editorialist: Dharsan R

DIFFICULTY:

SIMPLE

PREREQUISITES:

SORTING

PROBLEM:

Given an Array of Integers and an integer K, Find the difference between the sum of K largest elements and K smallest elements in the array.

EXPLANATION:

In order to find the K largest and smallest elements , we need to sort the array in ascending order and the last K elements will be the largest elements and the first K elements will be the smallest elements. Finding the sum of both and computing the difference will produce the required result.

SOLUTIONS:

Setter's Solution
for _ in range(int(input())):
    n,k=map(int,input().split())
    a=list(map(int,input().split()))
    a.sort()
    s=0 
    for i in range(k):
        s+=a[n-i-1]-a[i]
    print(s)