Maximize Happiness of Selected Children - Problem
You are given an array happiness of length n, and a positive integer k.
There are n children standing in a queue, where the i-th child has happiness value happiness[i]. You want to select k children from these n children in k turns.
In each turn, when you select a child, the happiness value of all the children that have not been selected till now decreases by 1. Note that the happiness value cannot become negative and gets decremented only if it is positive.
Return the maximum sum of the happiness values of the selected children you can achieve by selecting k children.
Input & Output
Example 1 — Basic Case
$
Input:
happiness = [1,2,3], k = 2
›
Output:
4
💡 Note:
Select children with happiness 3 and 2. Child with happiness 3 contributes 3, child with happiness 2 (after 1 decay) contributes 1. Total: 3 + 1 = 4
Example 2 — Larger Array
$
Input:
happiness = [1,1,1,1], k = 2
›
Output:
1
💡 Note:
All children have same happiness. Pick any 2: first contributes 1, second contributes 0 (after 1 decay). Total: 1 + 0 = 1
Example 3 — High Happiness Values
$
Input:
happiness = [2,3,4,5], k = 1
›
Output:
5
💡 Note:
Select the child with maximum happiness 5. No decay affects the selected child. Total: 5
Constraints
- 1 ≤ n ≤ 2 × 105
- 1 ≤ k ≤ n
- 1 ≤ happiness[i] ≤ 108
Visualization
Tap to expand
Understanding the Visualization
1
Initial State
Children with happiness values [1,2,3], need to select k=2
2
Greedy Selection
Always pick the child with highest current happiness
3
Maximum Sum
Optimal selection gives sum = 4
Key Takeaway
🎯 Key Insight: Use greedy strategy - always pick the child with highest current happiness, or mathematically: sort and use formula max(0, happiness[i] - i)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code