Skip to main content
Back to problems
Codeforces
Easy
Sorting
Arrays
Google
Puzzles

Choose the smallest possible range of puzzle pieces so that every student gets one piece and the maximum difference is minimized.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.
Problem Statement

Problem

You are given the sizes of nn puzzle pieces and need to distribute exactly mm pieces to mm students.

Each student must receive one puzzle piece. The unfairness of a distribution is the difference between the largest and the smallest piece chosen.

Your task is to choose mm pieces so that this unfairness is as small as possible.

Goal

Return the minimum possible value of:

max(selected)min(selected)\max(selected) - \min(selected)

among all groups of exactly mm pieces.

Input Format

  • The first line contains two integers nn and mm.
  • The second line contains nn integers describing the sizes of the puzzle pieces.

Output Format

  • Print one integer: the minimum possible unfairness.

Constraints

  • 1mn1 \le m \le n
  • Piece sizes are integers.
  • A valid selection always exists.

Hints

  • Sort the pieces first.
  • After sorting, consider every contiguous block of length mm and compute its range.

Constraints

  • Select exactly mm pieces.
  • Minimize the difference between the largest and smallest selected piece.
  • Sorting is allowed and typically essential.
Examples
Sample cases returned by the problem API.

Example 1

Input

7 3
10 100 300 200 1000 20 30

Output

20

Explanation

After sorting: 10 20 30 100 200 300 1000. The best group of 3 consecutive pieces is 10, 20, 30, giving unfairness 30 - 10 = 20.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.