˛
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 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.
Examples
Example 1:
| |
Example 2:
| |
Example 3:
| |
Solution
The objective is to maximize the total happiness sum by selecting children with the highest happiness values. A logical strategy is to prioritize choosing children with the highest happiness values first, considering that the happiness of unselected children decreases over time (and some unselected children can have at minimum 0 happiness).
This is a greedy problem, and we can solve it either using sorting or priority queue.
Video explanation
Here is the video explaining different methods in detail. Please check it out:
Method 1 - Sorting in ascending order and select from end
Algorithm
- Sort the
happinessarray say in ascending order (now most happy kids are at the end) - We start selecting the happiest child from end (as we sorted in ascending order)
- Reduce the happiness of next child by number of turns we have taken so far.
- Sum up all the happinesses.
Dry Run
happiness = [1,2,3], k = 2
- Sorting the array returns
[1,2,3] - As we have sorted in ascending order, we start from end of array for selecting happiest children. Also, we need
kelements from end, hencei>=n-k. - We select
3, add toansand increase turn by 1. (k = 1) - Then we select 2nd last child i.e.
2. We reduce it by 1 which is number of turns. Now, we add 1 to ans. (k = 2 and number of turns = 2) - As we have selected all the happy children, we return the ans.
Code
| |
Complexity
- ⏰ Time complexity:
O(n log n)- for sorting and thenO(n)for updatingans - 🧺 Space complexity:
O(1)
Method 2 - Sorting in descending order and select from start
This method is similar to previous method, but just starts solving from the start of the array.
Code
| |
Complexity
- ⏰ Time complexity:
O(n log n)- for sorting and thenO(n)for updatingans - 🧺 Space complexity:
O(1)
Method 3 - Using MaxHeap
- Create the max-heap
pqand allhappinessvalues. - Now, pick up the values from heap and subtract the number of turns
jand add to happiness values. - Return the happiness values.
Code
| |
Complexity
- ⏰ Time complexity:
O(n log n)-O(n)for creating heap and thenO(k log n)for extractingkelements from heap - 🧺 Space complexity:
O(n)