↓Skip to main content
  1. LeetCode/

LeetCode 3075: Maximize Happiness of Selected Children

·1 min· ·
LeetCode Medium Array Greedy Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2024-03-10

  • Submissions: Accepted (first try)

Approach
#

Each pick lowers everyone unpicked by 1, so the i-th pick (0-based) contributes max(happiness - i, 0). Picking from the largest down maximizes the total (Greedy Template 1): large values lose the least, and values stop at 0.

My Attempts
#

Passed on the first try during the 2024 contest by sorting and picking from the largest.

Solution
#

class Solution:
    def maximumHappinessSum(self, happiness: List[int], k: int) -> int:
        happiness.sort(reverse=True)
        return sum(max(h - i, 0) for i, h in enumerate(happiness[:k]))

Complexity
#

Time O(n log n), space O(1).

Mistakes to Avoid
#

  • Values stop at 0 and never go negative.
  • The answer may be large, but Python does not overflow.

Interview Explanation
#

The i-th pick loses i, so I sort descending, take the first k, and add each value minus i floored at 0. Time O(n log n).

Related

LeetCode 324: Wiggle Sort II
·2 mins
LeetCode Medium Array Divide-and-Conquer Greedy Sorting
LeetCode 324 note: sort, split into a small half and a large half, reverse each, and interleave with small values at even indices and large ones at odd indices
LeetCode 435: Non-overlapping Intervals
·2 mins
LeetCode Medium Array Dynamic-Programming Greedy Sorting
LeetCode 435 note: minimum removals = total minus the maximum kept; sort by right end and greedily keep the one ending earliest
LeetCode 3074: Apple Redistribution into Boxes
·1 min
LeetCode Easy Array Greedy Sorting
LeetCode 3074 note: apples can be split freely, so take boxes from the largest capacity until the total fits every apple
LeetCode 611: Valid Triangle Number
·2 mins
LeetCode Medium Array Two-Pointers Binary-Search Greedy
LeetCode 611 note: sort, fix the longest side k, and use two pointers for the shorter sides; when the sum is large enough every i in between works, adding j - i at once
LeetCode 2335: Minimum Amount of Time to Fill Cups
·1 min
LeetCode Easy Array Greedy Sorting Heap-Priority-Queue
LeetCode 2335 note: the answer is max(the largest count, ceil(total / 2)); simulating means filling one cup from each of the two largest every second
LeetCode 2357: Make Array Zero by Subtracting Equal Amounts
·1 min
LeetCode Easy Array Hash-Table Greedy Sorting
LeetCode 2357 note: each operation zeroes the group of the smallest positive value, so the answer is the number of distinct positive values