Maximize Happiness of Selected Children - Problem
Maximize Happiness of Selected Children
You're the organizer of a happiness distribution event for n children standing in a queue! Each child has a happiness value represented by happiness[i].
Here's the twist: You need to select exactly k children in k turns, but there's a catch! ๐ฏ
- After selecting a child in each turn, all remaining unselected children lose 1 happiness point
- Happiness values cannot go below zero (they stay at 0 once they reach it)
- Your goal is to maximize the total happiness of the selected children
Example: If happiness = [1, 2, 3] and k = 2, selecting the child with happiness 3 first gives us 3 points, then the remaining children have happiness [0, 1]. Selecting the child with happiness 1 gives us a total of 3 + 1 = 4.
Input & Output
example_1.py โ Basic Case
$
Input:
happiness = [1, 2, 3], k = 2
โบ
Output:
4
๐ก Note:
Select child with happiness 3 (gets 3 points), then remaining children have happiness [0, 1, 2]. Select child with happiness 2 (gets 1 point after decrease). Total: 3 + 1 = 4.
example_2.py โ All Children Selected
$
Input:
happiness = [1, 1, 1, 1], k = 4
โบ
Output:
1
๐ก Note:
First child gives 1 happiness, then all remaining become 0. Next selections give 0 each. Total: 1 + 0 + 0 + 0 = 1.
example_3.py โ Large Values
$
Input:
happiness = [2, 3, 4, 5], k = 1
โบ
Output:
5
๐ก Note:
Select the child with maximum happiness value 5. Since k=1, we only make one selection.
Constraints
- 1 โค n โค 2 ร 105
- 1 โค k โค n
- 1 โค happiness[i] โค 108
- All happiness values are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Sort by Happiness
Arrange children in descending order of happiness values
2
Greedy Selection
Select the happiest available child in each turn
3
Account for Decrease
Remember that happiness decreases by 1 after each selection
Key Takeaway
๐ฏ Key Insight: Always select the child with maximum current happiness first, because waiting will only decrease their happiness value. Greedy selection is optimal!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code