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
๐ŸŒŸ Maximize Happiness StrategyInput: happiness = [1, 2, 3], k = 2Step 1: Sort in descending order321Sorted: [3, 2, 1]Step 2: Turn 1 - Select child with happiness 33Selected! Adds 3 to totalTotal happiness: 3Step 3: Turn 2 - Select child with happiness 2 (now 1)1Selected! Adds max(0, 2-1) = 1Final total: 3 + 1 = 4
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!
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
28.9K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen