Question: there is a rocket ship which launches of any day from day 0 to day N and has F amount of fuel and is collecting samples but can only collect 1 sample each day and each day the fuel consumption is different for example day1: 12 ,day2: 32 ,day3: 5 etc. The program must output the most amount of days the rocket can be in space without running out of fuel.
I have succeeded in writing a correct solution however it is too slow, is there any data structure or another method of writing this program which would allow the program to run faster
code:
#!/usr/bin/env python
import sys
sys.setrecursionlimit(1000000000)
# N is the number of available days.
N = None
# F is the amount of fuel available.
F = None
# C contains the fuel needed to open a portal on each day.
C = [None for x in range(100005)]
answer = None
# Open the input and output files.
input_file = open("spacein.txt", "r")
output_file = open("spaceout.txt", "w")
# Read the value of N and F.
input_line = input_file.readline().strip()
N, F = map(int, input_line.split())
# Read the cost to open a portal on each day.
for i in range(0, N):
C[i] = int(input_file.readline().strip())
fuel = []
for i in range(0, N):
fuel.append(C[i])
print(fuel)
final = []
for i in range(0, len(fuel)-2):
for j in range(i+1, len(fuel)):
if fuel[i] + fuel[j] < F or fuel[i] + fuel[j] == F:
final.append(fuel.index(fuel[j])-fuel.index(fuel[i]))
print(fuel.index(fuel[i]), fuel.index(fuel[j]))
else:
pass
if len(fuel) > 2:
answer = (max(final)+1)
else:
answer = -1
# Write the answer to the output file.
output_file.write("%d\n" % (answer))
# Finally, close the input/output files.
input_file.close()
output_file.close()
