Skip to main content
Practice

Gym Uniform Problem Explanation

This program will solve the "Gym Uniform Problem" using the Greedy Algorithm.

The goal is to maximize the number of students who can participate in gym class by efficiently distributing gym uniforms among them.


Function Implementation

  1. Classify Students:

    • real_reserve is a list of students who have extra gym uniforms and haven't had theirs stolen.

    • real_lost is a list of students who lost their gym uniforms and don't have extras.

  2. Distribute Gym Uniforms:

    • For each student with extra gym uniforms (real_reserve), if a student with the previous number (r - 1) or the next number (r + 1) lacks a uniform (belongs to real_lost), lend the uniform to that student.

    • Remove the student who received a uniform from the real_lost list.

  3. Return Result:

    • Subtract the number of students without uniforms (len(real_lost)) from the total number of students (n) to return the number of students who can participate in gym class.

Model Solution
def solution(n, lost, reserve):
# Classify students
real_reserve = [r for r in reserve if r not in lost]
real_lost = [l for l in lost if l not in reserve]

# Distribute gym uniforms
for r in real_reserve:
if r - 1 in real_lost:
real_lost.remove(r - 1)
elif r + 1 in real_lost:
real_lost.remove(r + 1)

# Return result
return n - len(real_lost)

Example Usage

Input/Output Example
print(solution(5, [2, 4], [1, 3, 5]))  # Output: 5

In this example, out of 5 students, 2 lost their gym uniforms, and 3 have extras.

Students with extra uniforms can lend them to the students who are next to them.

Therefore, all students can participate in the gym class, and the function returns the total number of students, which is 5.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.