This is the "Popes" problem from UVa Online Judge:
On the occasion of Pope John Paul II's death, the American weekly magazine Time observed that the largest number of Popes to be selected in a 100-year period was 28, from 867 (Adrian II) to 965 (John XIII). This is a very interesting piece of trivia, but it would be much better to have a program to compute that number for a period of any length, not necessarily 100 years. Furthermore, the Catholic Church being an eternal institution, as far as we can predict it, we want to make sure that our program will remain valid per omnia secula seculorum.
Write a program that given the list of years in which each Pope was elected and a positive number \$Y\$, computes the largest number of Popes that were in office in a \$Y\$-year period, and the year of election for the first and last Popes in that period. Note that, given a year \$N\$, the \$Y\$-year period that starts in year \$N\$ is the time interval from the first day of year \$N\$ to the last day of year \$N+Y−1\$. In case of a tie, that is, if there is more than one \$Y\$-year period with the same largest number of Popes, your program should report only the most ancient one.
I am a Python beginner. When I submit this code, it says "time limit exceeded". How can I optimize this code?
while True:
try:
str=input()
if len(str):
Y = int( str )
else:
Y = int( input() )
except:
break
N_P = int( input() )
popes= []
for i in range (N_P):
popes.append( int(input()) )
Y = Y-1
maximum = 0
for i in range (N_P):
j = i
count = 0
while(popes[j] <= popes[i] + Y):
j = j+1
count = count +1
if j>= N_P:
break
if count>maximum:
maximum = count
first = popes[i]
last = popes[j-1]
print (maximum,first,last)