Skip to content

Added minimum waiting time problem solution using greedy algorithm #8701

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
May 1, 2023
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,7 @@
* [Fractional Knapsack](greedy_methods/fractional_knapsack.py)
* [Fractional Knapsack 2](greedy_methods/fractional_knapsack_2.py)
* [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py)
* [Minimum Waiting Time ](greedy_methods/minimum_waiting_time.py)

## Hashes
* [Adler32](hashes/adler32.py)
Expand Down
59 changes: 59 additions & 0 deletions greedy_methods/minimum_waiting_time.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""
This is a pure Python implementation for minimum waiting time problem using greedy
algorithm.
reference: https://www.youtube.com/watch?v=Sf3eiO12eJs

For doctests run following command:
python -m doctest -v minimum_waiting_time.py

The minimum_waiting_time function uses a greedy algorithm to calculate the minimum
time for queries to complete. It sorts the list in non-decreasing order, calculates
the waiting time for each query by multiplying its position in the list with the
sum of all remaining query times, and returns the total waiting time. A doctest
ensures that the function produces the correct output.
"""


def minimum_waiting_time(queries: list) -> int:
"""
This function takes a list of query times and returns the minimum waiting time
for all queries to be completed.

Args:
queries [list]: A list of queries

Returns:
total_waiting_time [int]: Minimum waiting time

Examples:
>>> minimum_waiting_time([3, 2, 1, 2, 6])
17
>>> minimum_waiting_time([3, 2, 1])
4
>>> minimum_waiting_time([1, 2, 3, 4])
10
>>> minimum_waiting_time([5, 5, 5, 5])
30
>>> minimum_waiting_time([])
0
"""
# Base case
n = len(queries)
if n == 0 or n == 1:
return 0

# Sort the list in non-decreasing order
queries.sort()

# Calculate the total waiting time
total_waiting_time = 0
for i in range(n - 1):
total_waiting_time += queries[i] * (n - i - 1)

return total_waiting_time


if __name__ == "__main__":
import doctest

doctest.testmod()