#3075
Medium Algorithms Maximize happiness of selected children
Array Greedy Sorting
58.7% acceptance
Feb 25, 2026
937
99
You are given an array happiness of length n, and a positive integer k.
There are n children standing in a queue, where the ith 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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn maximum_happiness_sum(mut happiness: Vec<i32>, k: i32) -> i64 {
happiness.sort_unstable_by(|a, b| b.cmp(a));
let mut sum = 0i64;
for (turn, &h) in happiness.iter().take(k as usize).enumerate() {
let val = (h - turn as i32).max(0);
sum += val as i64;
}
sum
}
}