#3075
Maximize Happiness of Selected Children
MediumArrayGreedySortingGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
In the optimal approach, we sort the happiness values in descending order and select the top k values. We account for the decrements based on the order of selection, which allows us to maximize the total happiness efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Sort the happiness array in descending order.
- 2Step 2: Select the top k happiness values.
- 3Step 3: For each selected happiness value, subtract the appropriate decrements based on its position in the selection.
solution.py6 lines
1def maxHappiness(happiness, k):
2 happiness.sort(reverse=True)
3 max_happiness = 0
4 for i in range(k):
5 max_happiness += max(0, happiness[i] - i)
6 return max_happinessℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, and the space complexity is O(1) since we are using a constant amount of extra space.
- 1Greedily selecting the largest happiness values maximizes the total happiness.
- 2Decrementing the happiness values based on the order of selection is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.