1723. Fading Delight
A party host is handing out exactly k prizes, one at a time, to children standing in a line. Child i has delight happiness[i] if picked right now, but every time a child is picked, the delight of all children not yet picked drops by 1 (it never goes below 0). A child's delight when picked is what counts toward your score.
Choose the order of the k picks to maximise the total delight collected and return it as a long. Sorting the delights in descending order and subtracting the pick number from each (floored at 0) gives the answer in O(n log n) time and O(1) extra space.
Example 1
- Input:
- happiness = [1,2,3], k = 2
- Output:
- 4
- Explanation:
Pick 3 first, then the child with 2 has dropped to 1, so the total is 4.
Example 2
- Input:
- happiness = [1,1,1,1], k = 2
- Output:
- 1
- Explanation:
The first pick gives 1 and the second child has already faded to 0, so the total is 1.
Example 3
- Input:
- happiness = [5,9,2,7], k = 4
- Output:
- 18
- Explanation:
Picking in the order 9, 7, 5, 2 yields 9 + 6 + 3 + 0 = 18.
Constraints
1 ≤ k ≤ n ≤ 1000
1 ≤ happiness[i] ≤ 108
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(1)