简体   繁体   中英

How to improve run time of while loop

I'm trying to use a greedy algorithm to solve the problem of refueling a car minimum number of times on a road trip. Unfortunately my code so far has exceeded the time limit in place for this problem.

I wanted to ask if the problem is coming from my nested while loop, because this seems to be the process that iterates the highest number of times. Here is the code:

def compute_min_refills(distance, tank, stations):
trip = distance
dist_traveled = 0

tank_capacity = tank
refills = 0 ##keeps track of total refills 

stations = stations
stations.append(trip) 

if tank > trip:
    return 0
elif station[-1] - station[-2] > tank:
    return -1
else:
    dist_traveled = tank
    while dist_traveled < trip:
        n = 0 
        while stations[n] <= dist_traveled:
            n+=1 
        if dist_traveled - stations[n-1] <= tank:
            refills+=1
        else:
            return -1
        dist_traveled = stations[n-1] + tank
        stations = stations[n-1:]
    return y

The constraints are as follows:

1 < distance < 10^5

1 < tank < 400

stations is an array containing at most 300 elements.

This is my first time dealing with problems of runtime so any advice even in how to approach the problem would be greatly appreciated.

You have several mistakes. First, you seem to assume that station is sorted, but I don't see where it's guaranteed. Even if it is, your append of append(trip) may break it.

elif station[-1] - station[-2] > tank:
    return -1

station[-1] and station[-2] may not matter, because they can be outside trip range. Moreover, they may not even exist.

while stations[n] <= dist_traveled:
   n+=1 

Possible arrayIndexOutOfBounds.

if dist_traveled - stations[n-1] <= tank:

Same issue.

n = 0 
...
stations = stations[n-1:]

Better to just set n = 0 outside outer while loop (and reuse n throughout different iterations).

if dist_traveled - stations[n-1] <= tank

Probably the cause of TL. This condition is satisfied when dist_traveled = stations[n-1] + tank ; after that you will assign dist_traveled to the exactly same value as it was before. Test: you have stations at coordinates 0 and tank + 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM