P2E - Editorial

PROBLEM LINK:
Practice
source
Author: SQU_Test

DIFFICULTY:
Easy

PREREQUISITES:
Sorting, Greedy.

PROBLEM:
Once Rashid got to a sale of old PC sets. There were n PC sets at that sale. PC set with index i costs a_i Rials. Some PC sets have a negative price — their owners are ready to pay Rashid if he buys their useless apparatus. Rashid can buy any PC sets he wants. Though he’s very strong, Rashid can carry at most m PC sets, and he has no desire to go to the sale for the second time. Please, help Rashid find out the maximum sum of money that he can earn.

EXPLANATION:
Negative elements are added to the array, sorted, we find the sum of m largest modulo.

TIME COMPLEXITY:
Time complexity of the solution is O(n log n) for sorting.

SOLUTIONS:

Setter’s Solution
T = int(input())
for t in range(T):
n,m = map(int,input().split())
p = list(map(int,input().split()))  
p.sort() 
tot = 0
for i in range(m):
  if p[i] < 0:
    tot+=p[i]
  else:
    break
print(-1*tot)