Skip to content
ExamSpine

Write it

Best score, recursively

A functionPython or Java11 tests, 7 of them hidden

On a phone? Put the lines in order instead

The puzzle game keeps the scores of its players in a list (an array in Java) called scores, in the order the games were played.

Write a recursive function that returns the highest score among the first n scores, that is scores[0] to scores[n - 1].

  1. Base case: when n is 1, the highest of the first score is scores[0].
  2. Recursive case: find the highest of the first n - 1 scores by calling the function itself, then compare that with scores[n - 1] and return the larger.
  3. n is always between 1 and the length of scores, and scores holds at most 500 scores. Scores after position n - 1 are not looked at.
  4. Scores are whole numbers between -1000 and 100000, so a score can be below 0.
  5. Write the comparison yourself. The shortcuts listed with this question are not allowed.

The tests check only the number your function returns, so they cannot tell a recursive answer from one that uses a loop. In the exam, a loop would not earn the marks for this part.

def best_score(scores: list[int], n: int) -> int

You cannot use these in this question:

  • max()
  • min()
  • sorted()
  • .sort()
  • import heapq
  • import functools

The question tests whether you can write the recursion and the comparison yourself, so the built-ins that find the largest value are not allowed.

Examples

Your function is tested on 11 cases: the 4 examples below, and 7 hidden ones that check the rules above.

  • best_score([40, 75, 10, 60], 4) should return 75: the highest of all four scores
  • best_score([40, 75, 10, 60], 1) should return 40: n is 1, the base case (rule 1)
  • best_score([12, 30, 55, 90], 3) should return 55: only the first three count, so 90 is not looked at (rule 3)
  • best_score([-8, -3, -15], 3) should return -3: every score below 0 (rule 4)

public static int bestScore(int[] scores, int n)

Checking whether Java answers can run here.

You cannot use these in this question:

  • Math.max()
  • Math.min()
  • Arrays.sort()
  • Arrays.stream()
  • Collections.max()
  • .sort()
  • .stream()
  • .max()
  • .min()
  • import java.util.stream

The question tests whether you can write the recursion and the comparison yourself, so the built-ins that find the largest value are not allowed.

Examples

Your function is tested on 11 cases: the 4 examples below, and 7 hidden ones that check the rules above.

  • bestScore(new int[]{40, 75, 10, 60}, 4) should return 75: the highest of all four scores
  • bestScore(new int[]{40, 75, 10, 60}, 1) should return 40: n is 1, the base case (rule 1)
  • bestScore(new int[]{12, 30, 55, 90}, 3) should return 55: only the first three count, so 90 is not looked at (rule 3)
  • bestScore(new int[]{-8, -3, -15}, 3) should return -3: every score below 0 (rule 4)
solution.pySolution.java