Maximize Happiness of Selected Children

You are given an array `happiness` of length `n` and a positive integer `k`. There are `n` children in a queue, where the `i`th child has happiness value `happiness[i]`. You pick `k` children over `k` turns. In each turn, after you pick a child, the happiness of **every child not yet picked** goes down by `1`. A happiness value never drops below `0`. Return *the **maximum** sum of the happiness values of the children you select*.

30:00

Maximize Happiness of Selected Children
medium
Free written solution
Topics
Companies

You are given an array happiness of length n and a positive integer k.

There are n children in a queue, where the ith child has happiness value happiness[i]. You pick k children over k turns.

In each turn, after you pick a child, the happiness of every child not yet picked goes down by 1. A happiness value never drops below 0.

Return the maximum sum of the happiness values of the children you select.

Example 1:
Input: {"happiness":[1,2,3],"k":2}
Output: 4
Constraints:
  • 1≤n==happiness.length≤2⋅1051 \leq n == \text{happiness.length} \leq 2 \cdot 10^5

  • 1≤happiness[i]≤1081 \leq \text{happiness}[i] \leq 10^8

  • 1≤k≤n1 \leq k \leq n

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"happiness":[1,2,3],"k":2}

3 children, pick 2. Every pick lowers the others by 1, so a child picked on turn i is worth happiness - i. Take the happiest children first.

children in the queue (unsorted)

1

2

3

0
1
2

gains:

none yet

picks

0/2

turn i (points lost)

-

total

0

value kept by a picked child
value lost while waiting
child picked this turn
Variables
VariableValue
i-
happiness[i]-
gain-
total0
DepthFunction Call
Stack empty
0/6