Skip to main content

Minimize Unhappy Students

medium

You are organizing a trip with limited capacity and need to assign students while minimizing dissatisfaction.

Problem

You are given an array groups of length n, where each element represents a student's friend group ID. Students with the same group ID belong to the same friend group.

You are also given an integer t, representing the maximum capacity of the trip.

Definitions

  • Friend Group Size: The number of students sharing the same group ID.
  • Unhappy Student: A student is unhappy if they are left behind while at least one member of their group is selected (i.e., their group is split).
  • If none of a group is selected, no one from that group is unhappy.

Objective

Select a subset of students (not exceeding capacity t) such that the total number of unhappy students is minimized.

Key Insight

  • Ideally, you want to select entire groups to avoid splitting.
  • However, when exact packing is not possible, you may need to partially include a group, which creates unhappy students.

Examples

Example 1:

Input: groups = [1,1,2,2,2,3,3], t = 4
Output: 0
Explanation:
Group sizes are [2,3,2]. Choosing groups of size 2 and 2 fills capacity exactly (2+2=4), so no group is split.

Example 2:

Input: groups = [1,1,2,2,2,3,3,4], t = 3
Output: 0
Explanation:
Group sizes are [2,3,2,1]. Selecting the group of size 3 fills capacity perfectly.

Notes

  • You may select students from multiple groups.
  • If you partially select a group of size k and include x students (0 < x < k), then k - x students are unhappy.

Approach Hint

This problem can be modeled as a variation of the knapsack problem, where:

  • Each group is an item with weight = size.
  • You want to maximize fully included students first.
  • Then consider partial inclusion if needed, minimizing leftover (unhappy students).

Example 1

Input

groups = [1,1,2,2,2,3,3], t = 4

Output

0

Explanation

Pick groups of size 2 and 2 to fill capacity exactly.

Example 2

Input

groups = [1,1,2,2,2,3,3,4], t = 3

Output

0

Explanation

Pick the group of size 3.

Constraints

  • 1 <= groups.length <= 10⁵
  • 1 <= groups[i] <= 10⁵
  • 1 <= t <= groups.length

OA

ArrayCountingDynamic ProgrammingHash TableSorting
Language
Code editor loads in the browser.

Output

Input

[1,1,2,2,2,3,3]
4

Expected

0

Your output

Run to see your output.