Skip to content

3075. Maximize Happiness of Selected Children 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  long long maximumHappinessSum(vector<int>& happiness, int k) {
    long ans = 0;
    int decremented = 0;

    ranges::sort(happiness, greater<>());

    for (int i = 0; i < k; ++i) {
      ans += max(0, happiness[i] - decremented);
      ++decremented;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public long maximumHappinessSum(int[] happiness, int k) {
    final int n = happiness.length;
    long ans = 0;
    int decremented = 0;

    Arrays.sort(happiness);

    for (int i = n - 1; i >= n - k; --i) {
      ans += Math.max(0, happiness[i] - decremented);
      ++decremented;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def maximumHappinessSum(self, happiness: list[int], k: int) -> int:
    ans = 0
    decremented = 0

    happiness.sort(reverse=True)

    for i in range(k):
      ans += max(0, happiness[i] - decremented)
      decremented += 1

    return ans