We are well into the 21st century and school children are taught dynamic programming in class 4. The IOI training camp has degenerated into an endless sequence of tests, with negative marking. At the end of the camp, each student is evaluated based on the sum of the best contiguous segment (i.e., no gaps) of marks in the overall sequence of tests.
Students, however, have not changed much over the years and they have asked for some relaxation in the evaluation procedure. As a concession, the camp coordinators have agreed that students are allowed to drop upto a certain number of tests when calculating their best segment.
For instance, suppose that Lavanya is a student at the training camp and there have been ten tests, in which her marks are as follows.
Test 1 2 3 4 5 6 7 8 9 10
Marks 6 -5 3 -7 6 -1 10 -8 -8 8
In this case, without being allowed to drop any tests, the best segment is tests 5–7, which yields a total of 15 marks. If Lavanya is allowed to drop upto 2 tests in a segment, the best segment is tests 1–7, which yields a total of 24 marks after dropping tests 2 and 4. If she is allowed to drop upto 6 tests in a segment, the best total is obtained by taking the entire list and dropping the 5 negative entries to get a total of 33.
You will be given a sequence of N test marks and a number K. You have to compute the sum of the best segment in the sequence when upto K marks may be dropped from the segment.
Answers
Answered by
2
Answer:
def sumsub(ls,k):
if k==0:
return(sum(ls))
else:
ls.sort()
if len(ls)>=k:
for j in range(0,k):
if(ls[0]<0):
ls.remove(ls[0])
return(sum(ls))
else:
for i in range(len(ls)):
if ls[0]<0:
ls.remove(ls[0])
return(sum(ls))
n,k= map(int,input().split(" "))
l=[]
smax=0
for i in range(n):
m=input()
l.append(int(m))
for i in range(n):
for j in range(n,0,-1):
s=sumsub(l[i:j],k)
if s>smax :
smax=s
print(smax)
Explanation:
Similar questions