430. Select Exam Marks Closest to a Target
Asked in
Select Exam Marks Closest to a Target

After an exam, a school arranges all students' marks from lowest to highest.

A teacher wants to review a fixed number of marks closest to a target mark. Select those marks and return them in non-decreasing order.

Class

ExamMarkSelector

Method

chooseClosestMarks

List<Integer> chooseClosestMarks(List<Integer> sortedMarks, int markCount, int targetMark)

Parameters

  • sortedMarks: The students' marks in non-decreasing order.
  • markCount: The number of marks to return.
  • targetMark: The mark to which all available marks are compared.

Returns

Return a list containing exactly markCount marks closest to targetMark. The returned list must be in non-decreasing order.

Selection Rules

  • The mark with the smaller absolute difference from targetMark is considered closer.
  • If two marks have the same absolute difference, the lower mark is considered closer.
  • Marks belonging to different students are treated separately, even when their values are equal.

Constraints

  • 1 ≤ sortedMarks.size() ≤ 10,000
  • 1 ≤ markCount ≤ sortedMarks.size()
  • 0 ≤ sortedMarks.get(i) ≤ 100 for 0 ≤ i < sortedMarks.size()
  • 0 ≤ targetMark ≤ 100
  • sortedMarks.get(i) ≤ sortedMarks.get(i + 1) for every 0 ≤ i < sortedMarks.size() - 1.

Example 1

chooseClosestMarks( sortedMarks = List.of(14, 26, 38, 51, 64, 79, 93), markCount = 4, targetMark = 58 )

Output: List.of(38, 51, 64, 79)

These four marks have the smallest differences from 58.

Example 2

chooseClosestMarks( sortedMarks = List.of(15, 35, 55, 75, 95), markCount = 3, targetMark = 65 )

Output: List.of(35, 55, 75)

Marks 35 and 95 are equally far from 65. Since only one of them is needed, the lower mark 35 is selected.

Example 3

chooseClosestMarks( sortedMarks = List.of(18, 34, 47, 66, 82), markCount = 3, targetMark = 98 )

Output: List.of(47, 66, 82)

The target mark is greater than every available mark, so the three highest marks are closest.

Example 4

chooseClosestMarks( sortedMarks = List.of(42, 58, 58, 58, 73, 87), markCount = 4, targetMark = 62 )

Output: List.of(58, 58, 58, 73)

The three students with 58 marks are all included. The mark 73 is the next closest value.



Please use Laptop/Desktop or any other large screen to add/edit code.