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
Maximize Happiness of Selected Children INPUT n children in queue 1 h=1 2 h=2 3 h=3 happiness array: 1 2 3 [0] [1] [2] Input Values: happiness = [1, 2, 3] k = 2 (select 2 children) ALGORITHM STEPS (Greedy Approach) 1 Sort Descending [3, 2, 1] - highest first 2 Turn 1: Pick h=3 Contribute: 3-0 = 3 3 Turn 2: Pick h=2 Contribute: max(2-1,0) = 1 4 Sum Results Total = 3 + 1 = 4 Selection Table Turn Pick Decay Add 1 3 0 3 2 2 1 1 FINAL RESULT Selected Children: 3 Turn 1 2 Turn 2 Calculation: (3 - 0) + (2 - 1) = 3 + 1 = 4 Maximum Happiness 4 OK - Optimal Solution Key Insight: Greedy works because picking the highest happiness child first maximizes gain before decay affects it. At turn i (0-indexed), the i-th largest value contributes max(happiness[i] - i, 0) to the sum. Time: O(n log n) for sorting | Space: O(1) or O(n) depending on sort TutorialsPoint - Maximize Happiness of Selected Children | Greedy Approach
Asked in
Google 45 Amazon 38 Microsoft 32
23.4K Views
Medium Frequency
~25 min Avg. Time
890 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