Here is my solution to the Lead Game problem on Codechef. It runs fine, but took 2.63 sec and 3.8M memory, while I saw many C programs that had completed in 0.08 seconds and 1.6M memory. How can I make it faster?
import sys
cnt = int(sys.stdin.readline())
match = [[int(x) for x in sys.stdin.readline().split()] for i in range(cnt)]
diff=[]
for i in range(cnt):
if i!=0:
match[i]=[sum(vals) for vals in zip(match[i-1],match[i])]
diff.append([1 if max(match[i])==match[i][0] else 2,abs(match[i][0]-match[i][1])])
maxval = max(diff,key=lambda x:x[1])
sys.stdout.write(str(maxval[0]) + ' ' + str(maxval[1]))
I wouldn’t worry about the memory footprint (Python data structures take a little more space, and it’s normal) and also it’s hard to expect a Python script to beat a C program in terms of speed.
Edit: no need to keep leads history
My O(n) algorithm ran in 1.18 seconds:
Edit
To see where your algorithm spends most time you can use: