Skip to content

Commit 4ce4dd5

Browse files
Himanshutomar31pre-commit-ci[bot]
authored andcommitted
Added minimum waiting time problem solution using greedy algorithm (TheAlgorithms#8701)
* Added minimum waiting time problem solution using greedy algorithm * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * ruff --fix * Add type hints * Added two more doc test * Removed unnecessary comments * updated type hints * Updated the code as per the code review --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 1069240 commit 4ce4dd5

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

Diff for: DIRECTORY.md

+1
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,7 @@
450450
* [Fractional Knapsack](greedy_methods/fractional_knapsack.py)
451451
* [Fractional Knapsack 2](greedy_methods/fractional_knapsack_2.py)
452452
* [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py)
453+
* [Minimum Waiting Time ](greedy_methods/minimum_waiting_time.py)
453454

454455
## Hashes
455456
* [Adler32](hashes/adler32.py)

Diff for: greedy_methods/minimum_waiting_time.py

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
Calculate the minimum waiting time using a greedy algorithm.
3+
reference: https://www.youtube.com/watch?v=Sf3eiO12eJs
4+
5+
For doctests run following command:
6+
python -m doctest -v minimum_waiting_time.py
7+
8+
The minimum_waiting_time function uses a greedy algorithm to calculate the minimum
9+
time for queries to complete. It sorts the list in non-decreasing order, calculates
10+
the waiting time for each query by multiplying its position in the list with the
11+
sum of all remaining query times, and returns the total waiting time. A doctest
12+
ensures that the function produces the correct output.
13+
"""
14+
15+
16+
def minimum_waiting_time(queries: list[int]) -> int:
17+
"""
18+
This function takes a list of query times and returns the minimum waiting time
19+
for all queries to be completed.
20+
21+
Args:
22+
queries: A list of queries measured in picoseconds
23+
24+
Returns:
25+
total_waiting_time: Minimum waiting time measured in picoseconds
26+
27+
Examples:
28+
>>> minimum_waiting_time([3, 2, 1, 2, 6])
29+
17
30+
>>> minimum_waiting_time([3, 2, 1])
31+
4
32+
>>> minimum_waiting_time([1, 2, 3, 4])
33+
10
34+
>>> minimum_waiting_time([5, 5, 5, 5])
35+
30
36+
>>> minimum_waiting_time([])
37+
0
38+
"""
39+
n = len(queries)
40+
if n in (0, 1):
41+
return 0
42+
return sum(query * (n - i - 1) for i, query in enumerate(sorted(queries)))
43+
44+
45+
if __name__ == "__main__":
46+
import doctest
47+
48+
doctest.testmod()

0 commit comments

Comments
 (0)