# Solved! Leetcode 3075. Maximize Happiness of Selected Children

Source: https://leetcode.com/problems/maximize-happiness-of-selected-children/description/

## Description: Maximize Happiness of Selected Children

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.

## Constraints

• `1 <= n == happiness.length <= 2 * 105`
• `1 <= happiness[i] <= 108`
• `1 <= k <= n`

## Solution

### Time Complexity

O(nlogn), where n is the size of the array happiness

### Space Complexity

O(log(n)), where n is the size of the array happiness

Note: in java sort is implemented as a variant of quicksort which has space complexity of O(Log (n))

In the case of objects, java is going to use a hybrid between mergesort and insertion sort , called TimSort, which has O(n) space complexity. For primitive types, java will use a dual pivot variation of quicksort, which has O(log(n)) space complexity.

Rate this post