n = int(input())
c = list(map(int,input().strip().split()))
if n <= 3:
print(min(c))
else:
cost = [c[0],c[1],c[2]]
for i in range(3,n):
cost.append(c[i] + min(cost[i-3:i]))
print(min(cost[n-3:]))
This is giving accepted for all test cases except for test case 2 in which it is giving Runtime Error. Can someone tell me the reason or provide a test case where it fails.
So what I have done is that-
Cost[i] = min time if we work that day.
So cost[0] = c[0],
cost[1] = c[1],
cost[2] = c[2]
And for the rest it is c[i] + min of the previous 3 elements.
And the answer is the min of the last 3 elements.
Probably I would use c = raw_input(); timeList = c.split(" "); #### then a for loop for converting it to int list rather than list(map(int,input().strip().split())) but thats all upto you , i prefer the previous one for its readability and easy to debug’ness’.
OK, so I finally found the bug. I submitted a solution which was the following-
Take the input. That’s it.
It was still showing error on test-case 2.
Then I submitted a solution in which it said that if there’s a character which is non numeric and it is not a space then it raises an error and it did on test case 2.
So finally I submitted a solution in which it took input in such a way that it did not include alphabetical characters and I got AC.
Thanks by the way mz54. I don’t have enough karma to upvote else I would have upvoted your help.
Here is my solution-
n = int(input().strip())
c = input().strip().split()
j = 0
while j < n:
try:
c[j] = int(c[j])
except:
pass
finally:
j += 1
n = len(c)
if n <= 3:
print(min(c))
else:
for i in range(3,n):
c[i] += min(c[i-3:i])
print(min(c[n-3:]))
The same thing happened in the problem Wormholes in which the problem was that it said that the next n lines will give the time of the contest but in 2 test cases there were not n lines but less then that so I was taking extra input and again I had to add a try-except block.
Thanks a lot @mathecodician. I had been trying to solve that SUPW problem for months and everytime it gave me error on the second test. Your suggestion to take input in such a way so that it does not include characters other than numbers helped a lot. It finally worked after 30-40 tries!! Thanks a lot!
For Java users, just do the conversion from String to integer inside the try block and also make a catch block to catch the exception. Like this:-
N=Integer.parseInt(br.readLine()); //array length
String s[]=br.readLine().trim().split(" "); //accepting the time for each SUPW work
int a[]=new int[N];
for(i=0;i<N;i++) //converting from String to integer
{
int ch=0;
try
{
ch=Integer.parseInt(s[i].trim());
}
catch(Exception e)
{
}
a[i]=ch;
}