Top K Sum From Mixed Tokens
Python
Hard
2 views
Problem Description
Read n tokens and integer k. Consider only tokens that are valid integers. If there are less than k valid integers, output ERROR. Else output sum of k largest valid integers.
Input Format
First line n k. Second line n tokens.
Output Format
One integer sum or ERROR.
Sample Test Case
Input:
8 3
5 x 10 -2 7 bad 9 1
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if len(lines)<2: sys.exit(0)
first=lines[0].split()
if len(first)<2:
sys.stdout.write('ERROR')
raise SystemExit
n=int(first[0]); k=int(first[1])
toks=lines[1].split()[:n]
arr=[]
for t in toks:
try:
arr.append(int(t))
except Exception:
pass
if len(arr)<k:
sys.stdout.write('ERROR')
else:
arr.sort(reverse=True)
sys.stdout.write(str(sum(arr[:k])))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!