[LeetCode] 3075. Maximize Happiness of Selected Children

CNoodle發表於2024-05-10

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.

Example 1:
Input: happiness = [1,2,3], k = 2
Output: 4
Explanation: We can pick 2 children in the following way:

  • Pick the child with the happiness value == 3. The happiness value of the remaining children becomes [0,1].
  • Pick the child with the happiness value == 1. The happiness value of the remaining child becomes [0]. Note that the happiness value cannot become less than 0.
    The sum of the happiness values of the selected children is 3 + 1 = 4.

Example 2:
Input: happiness = [1,1,1,1], k = 2
Output: 1
Explanation: We can pick 2 children in the following way:

  • Pick any child with the happiness value == 1. The happiness value of the remaining children becomes [0,0,0].
  • Pick the child with the happiness value == 0. The happiness value of the remaining child becomes [0,0].
    The sum of the happiness values of the selected children is 1 + 0 = 1.

Example 3:
Input: happiness = [2,3,4,5], k = 1
Output: 5
Explanation: We can pick 1 child in the following way:

  • Pick the child with the happiness value == 5. The happiness value of the remaining children becomes [1,2,3].
    The sum of the happiness values of the selected children is 5.

Constraints:
1 <= n == happiness.length <= 2 * 105
1 <= happiness[i] <= 108
1 <= k <= n

幸福值最大化的選擇方案。

給你一個長度為 n 的陣列 happiness ,以及一個 正整數 k 。

n 個孩子站成一隊,其中第 i 個孩子的 幸福值 是 happiness[i] 。你計劃組織 k 輪篩選從這 n 個孩子中選出 k 個孩子。

在每一輪選擇一個孩子時,所有 尚未 被選中的孩子的 幸福值 將減少 1 。注意,幸福值 不能 變成負數,且只有在它是正數的情況下才會減少。

選擇 k 個孩子,並使你選中的孩子幸福值之和最大,返回你能夠得到的 最大值 。

思路

思路是排序。把 input 陣列排序,之後按照從大到小開始掃描陣列。每遇到一個孩子的時候,先按照規則將他的幸福值減去相應的數值,比如之前已經選擇了 X 個孩子,就需要把當前孩子的幸福值 - X。做過這個減法之後,如果當前孩子的幸福值還大於 0 的話,就把當前孩子的幸福值累加到結果裡。

複雜度

時間O(nlogn)
空間O(1)

程式碼

Java實現

class Solution {
    public long maximumHappinessSum(int[] happiness, int k) {
        long res = 0;
        Arrays.sort(happiness);
        int deduct = 0;
        int n = happiness.length;
        for (int i = n - 1; i >= 0 && k > 0; i--) {
            happiness[i] = Math.max(0, happiness[i] - deduct);
            res += happiness[i];
            deduct++;
            k--;
        }
        return res;
    }
}

相關文章