Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 1 addition & 14 deletions src/main/java/other/RecursionMax.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,7 @@
public class RecursionMax {

public static int recursionMax(List<Integer> array) {
if (array == null) {
return -1;
}
if (array.isEmpty()) {
return -1;
}
return recursionMax(array, 0, Integer.MIN_VALUE);
}

private static int recursionMax(List<Integer> array, int index, int currentMax) {
if (index == array.size()) {
return currentMax;
}
return recursionMax(array, index + 1, Math.max(currentMax, array.get(index)));
return max(array);
}

public static int max(List<Integer> array) {
Expand Down
8 changes: 8 additions & 0 deletions src/test/java/other/RecursionMaxTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Tag;
Expand All @@ -29,6 +30,13 @@ void shouldNotMutateInputList() {
assertEquals(List.of(3, 8, 1, 5), values);
}

@Test
void shouldHandleLargeListsWithoutExhaustingTheStack() {
List<Integer> values = Collections.nCopies(100_000, 42);

assertEquals(42, RecursionMax.recursionMax(values));
}

private static Stream<Arguments> maxCases() {
return Stream.of(
Arguments.of(null, -1),
Expand Down