Problem Description
You are given an array of positive integers representing the happiness values of n children standing in a queue and a positive integer k. In k turns, you select one child per turn. When a child is selected, the happiness value of every child who is not yet selected decreases by 1 (if it is positive). Your goal is to maximize the total sum of the happiness values of the selected children.
Key Insights
- The order of selection matters: earlier selections avoid more decrements.
- When a child is selected at turn r, its effective contribution is max(happiness - (r - 1), 0).
- To maximize the contribution, assign early turns to the children with the highest happiness values.
- Sorting the array in descending order and then selecting the first k children (with each child’s effective happiness reduced by its turn index) yields the optimal solution.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting. Space Complexity: O(n) for storing the sorted array (or O(1) if sorting in-place).
Solution
We start by sorting the given array in descending order so that the child with the highest happiness comes first. For each of the first k children in the sorted list, compute its contribution by subtracting its turn index (starting from 0) from its initial happiness, ensuring the value does not drop below 0. Summing these contributions gives the maximum total happiness. The greedy approach works because high-value children lose less additional value when chosen earlier.