-2

I was assigned this problem I have to solve:

There are plenty of guided activities in a certain swimming pool. Therefore, the usage rules are very strict:

The free time slots are only one minute long. After using a free slot, we must wait for at least x seconds before using another slot. You have the list of free slots, and you want to swim for at least m minutes. What is the maximum x that allows it?

Input

Input consists of several cases. Every case begins with the number of minutes m and the number of slots n, followed by n triples H:M:S, indicating that there is a lane that is free for one minute starting at H:M:S. Assume 2 ≤ m ≤ n ≤ 1000, that the hours are between 00:00:00 and 23:59:00, and that there are no overlaps between time slots. The final entry is marked with a special case with m = n = 0.

Output

For every case, print the maximum x that permits a total bath time of m or more minutes.

What would be a possible implementation using binary search over the variable x to maximize it?

Outputs of the problem:

input: 
4 8 
00:10:40 00:35:30 01:00:00 01:55:00 02:10:00 03:15:00 12:00:20 23:59:00 
output: x = 11000
venkatvb
  • 681
  • 1
  • 9
  • 24
Marc Ortiz
  • 2,242
  • 5
  • 27
  • 46

1 Answers1

2

This doesn't require any search at all. Transform the list from free time-slots to a list of waiting-time between timeslots in seconds (take into account you're swimming for one minute):

waiting_time[]

for i in [1, length(time_slots))
   waiting_time[i - 1] = delta_minutes(time_slots[i - 1], time_slots[i]) * 60 - 60

Sort the list of waiting-times

sortDesc(waiting_time)

Since you've got to wait m - 1 times, x must be chosen such that at least x waiting-times are at least equally long. Since we're searching for the maximum x, the smallest waiting-time must be exactly as long as x, which is the m - 1th element in our array.

Putting it all together:

minX(input[], m):
     waiting_time[]

     for i in [1, length(input)):
         waiting_time[i - 1] = delta_minutes(time_slots[i - 1], time_slots[i]) * 60 - 60

     sortDesc(waiting_time)

     return waiting_time[m - 1]
  • admittedly the question was very broad, but it was tagged `C++` not `python`. – m8mble Nov 20 '16 at 16:03
  • @m8mble well, this is pseudocode, not python. I'm willing to present a solution to your problem, but I won't write the full code for you. –  Nov 20 '16 at 16:46