Skip to content

Commit 5bf765c

Browse files
committed
feat: Add MinimumWaitingTime new algorithm with Junit tests
1 parent 213fd5a commit 5bf765c

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* The MinimumWaitingTime class provides a method to calculate the minimum
7+
* waiting time for a list of queries using a greedy algorithm.
8+
*
9+
* @author Hardvan
10+
*/
11+
public class MinimumWaitingTime {
12+
13+
/**
14+
* Calculates the minimum waiting time for a list of queries.
15+
* The function sorts the queries in non-decreasing order and then calculates
16+
* the waiting time for each query based on its position in the sorted list.
17+
*
18+
* @param queries an array of integers representing the query times in picoseconds
19+
* @return the minimum waiting time in picoseconds
20+
*/
21+
public static int minimumWaitingTime(int[] queries) {
22+
int n = queries.length;
23+
if (n <= 1) {
24+
return 0;
25+
}
26+
27+
Arrays.sort(queries);
28+
29+
int totalWaitingTime = 0;
30+
for (int i = 0; i < n; i++) {
31+
totalWaitingTime += queries[i] * (n - i - 1);
32+
}
33+
return totalWaitingTime;
34+
}
35+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import java.util.stream.Stream;
6+
import org.junit.jupiter.params.ParameterizedTest;
7+
import org.junit.jupiter.params.provider.Arguments;
8+
import org.junit.jupiter.params.provider.MethodSource;
9+
10+
public class MinimumWaitingTimeTest {
11+
12+
@ParameterizedTest
13+
@MethodSource("provideTestCases")
14+
public void testMinimumWaitingTime(int[] queries, int expected) {
15+
assertEquals(expected, MinimumWaitingTime.minimumWaitingTime(queries));
16+
}
17+
18+
private static Stream<Arguments> provideTestCases() {
19+
return Stream.of(Arguments.of(new int[] {3, 2, 1, 2, 6}, 17), Arguments.of(new int[] {3, 2, 1}, 4), Arguments.of(new int[] {1, 2, 3, 4}, 10), Arguments.of(new int[] {5, 5, 5, 5}, 30), Arguments.of(new int[] {}, 0));
20+
}
21+
}

0 commit comments

Comments
 (0)