Hello everyone, in this series, we will solve many LeetCode problems together. I hope this helps you improve your skills and learn about data structures and algorithms.
Today, we are going to solve problem number 3075: Maximize Happiness of Selected Children.
So, we have an array called happiness with length "n", and a positive integer k.
There are n children standing in a queue, where each child has a value happiness[i]. We want to select k children from the 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. The happiness value cannot become negative and only decreases if it is positive.
Return the maximum sum of the values of the selected children you can select in k turns.
Okay, first, we will sort the array.
In each turn, when we select the largest value from the array, we must decrease each remaining item in the array.
Now, let's proceed. I'll create a variable called total to save the result and a variable called count to save the number of selected items. Each time we select an item, we'll increment count by one.
So, for each index i from happiness.length to 0:
We'll check if count is less than k and happiness[i] - count is greater than or equal to 0. If so, total will be updated to total + (happiness[i] - count), and count will be incremented. Okay, now let's submit the solution.
Alright, it's done. Thank you, everyone, for watching my video. If you enjoyed it, please like and follow me on YouTube.
Thank you
/**
* @param {number[]} happiness
* @param {number} k
* @return {number}
*/
var maximumHappinessSum = function (happiness, k) {
const arr = happiness.sort((a, b) => a - b);
let total = 0;
let count = 0;
for (let i = arr.length - 1; i >= 0; i--) {
if (count < k && arr[i] - count >= 0) {
console.log(count);
total += arr[i] - count;
count++;
}
}
return total;
};