Talentd
FleetCode
Make and follow sheets.Sign in

Maximize Happiness of Selected Children solution and explanation

MediumArrayGreedySorting6 min read58.7% acceptanceUpdated 9 Apr 2026
Maximize Happiness of Selected Children | Sorting | Max Heap | Leetcode 3075 | codestorywithMIKcodestorywithMIK · 15:08 · 6K viewsWatch on YouTube
9 more videos on this problem
  1. Maximize Happiness of Selected Children | Sorting | Max Heap | Leetcode 3075 | codestorywithMIKcodestorywithMIK · 15:08 · 6K views
  2. 3075. Maximize Happiness of Selected Children | GreedyAryan Mittal · 6:33 · 1K views
  3. Leetcode | 3075. Maximize Happiness of Selected Children | Medium | JavaDeveloper Docs · 8:48 · 965 views
  4. Maximize Happiness of Selected Children | Greedy | Heap | Sorting | Leetcode 3075Techdose · 14:49 · 432 views
  5. 3075. Maximize Happiness of Selected Children | Leetcode Daily - PythonLeetcode Daily · 8:54 · 376 views
  6. LeetCode 3075 - Maximize Happiness of Selected Children - PythonAlpha-Code · 5:33 · 112 views
  7. leetcode 3075 Maximize Happiness of Selected Children greedily pick the largestsCode-Yao · 7:23 · 88 views
  8. Maximize Happiness of Selected Children | LeetCode 3075 | PythonMad Dev Canvas · 18:46 · 86 views
  9. Maximize Happiness of Selected Children | LeetCode 3075 | Java Code | Developer CoderDeveloper Coder · 15:32 · 72 views
  10. Leetcode 3075: Maximize Happiness of Selected Children (Medium)TechieGanesh · 5:39 · 55 views

The problem

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

Approach overview

Problem Overview: You are given an array where happiness[i] represents the happiness value of the i-th child. When you select a child, their happiness contributes to the total, but every subsequent selection reduces remaining children's happiness by 1. The goal is to choose k children that maximize the final happiness sum.

Approach 1: Sorting + Greedy (O(n log n) time, O(1) extra space)

The key observation: the earlier you select a child, the less their happiness gets reduced. So the children with the largest happiness values should be chosen first. Sort the array in descending order using a sorting technique, then iterate through the first k elements. For the i-th selection, the effective contribution becomes max(happiness[i] - i, 0) because each previous pick decreases remaining happiness by 1. Accumulate these values until you either pick k children or the contribution becomes zero. This greedy ordering guarantees the maximum total happiness.

This works because picking a smaller value earlier would only reduce the contribution of a larger value later. Greedy ordering after sorting ensures the largest possible contributions happen when the reduction factor is smallest. The algorithm primarily uses operations on an array and a greedy decision process.

Approach 2: Hash Map Counting (O(n + U log U) time, O(U) space)

Instead of sorting the full array, you can count frequencies of each happiness value using a hash map. After building the map, process values from highest to lowest and simulate picking children while applying the decreasing penalty. Each time you select a child with value v, the actual contribution becomes v - selected. Continue until k selections are made or contributions drop to zero.

This approach reduces redundant comparisons when many children share the same value. It still follows the same greedy principle: always take the largest available happiness first. The hash structure helps aggregate duplicates and iterate through unique values in descending order.

Recommended for interviews: The sorting + greedy solution is the expected approach. It is simple, easy to reason about, and runs in O(n log n) time with constant extra space. Explaining why picking the largest values first maximizes the sum demonstrates strong greedy intuition. Mentioning the hash map counting variant shows awareness of optimization techniques when duplicates are common.

Approach 1: Sorting Approach

This approach involves sorting the input data first and then finding the solution by traversing through the sorted data. This approach is generally straightforward and often leads to a solution by leveraging sorted order, which simplifies many problems, such as finding pairs or detecting duplicates.

def solve(arr):
    arr.sort()
    print(' '.join(map(str, arr)))
import java.util.Arrays;

public class Solution {
    public static void solve(int[] arr) {
        Arrays.sort(arr);
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}
#include <iostream>
#include <algorithm>
#include <vector>

void solve(std::vector<int>& arr) {
    std::sort(arr.begin(), arr.end());
    for(int num : arr) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
}
function solve(arr) {
    arr.sort((a, b) => a - b);
    console.log(arr.join(' '));
}
#include <stdio.h>
#include <stdlib.h>

int compare(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}

void solve(int* arr, int n) {
    qsort(arr, n, sizeof(int), compare);
    // Perform operations on sorted arr
    for(int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}
using System;
using System.Linq;

public class Solution {
    public static void Solve(int[] arr) {
        Array.Sort(arr);
        Console.WriteLine(string.Join(" ", arr));
    }
}

The Python solution sorts the list using the list sort method and prints the elements in a single line. After sorting, you can implement the specific logic for the problem.

Complexity

Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) due to the input list.

Try this approach in the editor

Approach 2: Hash Map Approach

This approach leverages a hash map to efficiently solve problems requiring quick lookups or to detect duplicates. This method is optimal for problems where you need to count occurrences or require O(1) average-time complexity for lookups.

def solve(arr):
    hash_map = {}
    for num in arr:
        hash_map[num] = hash_map.get(num, 0) + 1
    for num, count in hash_map.items():
        print(f'{num} appears {count} times')
import java.util.HashMap;

public class Solution {
    public static void solve(int[] arr) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : arr) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        for (int key : map.keySet()) {
            System.out.println(key + " appears " + map.get(key) + " times");
        }
    }
}
#include <iostream>
#include <unordered_map>
#include <vector>

void solve(std::vector<int>& arr) {
    std::unordered_map<int, int> hash;
    for(int num : arr) {
        hash[num]++;
    }
    for(const auto& entry : hash) {
        std::cout << entry.first << " appears " << entry.second << " times\n";
    }
}
function solve(arr) {
    const map = new Map();
    for (const num of arr) {
        map.set(num, (map.get(num) || 0) + 1);
    }
    map.forEach((count, num) => {
        console.log(`${num} appears ${count} times`);
    });
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 1000

void solve(int* arr, int n) {
    int hash[MAX];
    memset(hash, 0, sizeof(hash));
    for(int i = 0; i < n; i++) {
        hash[arr[i]]++;
    }
    // Example to print all numbers and their counts
    for(int i = 0; i < MAX; i++) {
        if(hash[i] > 0) {
            printf("%d appears %d times\n", i, hash[i]);
        }
    }
}
using System;
using System.Collections.Generic;

public class Solution {
    public static void Solve(int[] arr) {
        Dictionary<int, int> map = new Dictionary<int, int>();
        foreach (int num in arr) {
            if (map.ContainsKey(num)) {
                map[num]++;
            } else {
                map[num] = 1;
            }
        }
        foreach (var key in map.Keys) {
            Console.WriteLine($"{key} appears {map[key]} times");
        }
    }
}

This Python solution employs a dictionary to count how many times each number appears in the list, efficiently providing results for counting duplicates or frequency transformations.

Complexity

Time Complexity: O(n)
Space Complexity: O(n) for the dictionary used as a hash map.

Try this approach in the editor

Approach 3: Greedy + Sorting

To maximize the sum of happiness values, we should prioritize selecting children with higher happiness values. Therefore, we can sort the children in descending order by happiness value, and then select k children in sequence. For the current i-th child, the happiness value obtained is max(happiness[i] - i, 0). Finally, return the sum of happiness values of these k children.

The time complexity is O(n times log n + k), and the space complexity is O(log n), where n is the length of the array happiness.

function maximumHappinessSum(happiness: number[], k: number): number {
    happiness.sort((a, b) => b - a);
    let ans = 0;
    for (let i = 0; i < k; ++i) {
        const x = happiness[i] - i;
        ans += Math.max(x, 0);
    }
    return ans;
}
func maximumHappinessSum(happiness []int, k int) (ans int64) {
	sort.Ints(happiness)
	for i := 0; i < k; i++ {
		x := happiness[len(happiness)-i-1] - i
		ans += int64(max(x, 0))
	}
	return
}
impl Solution {
    pub fn maximum_happiness_sum(mut happiness: Vec<i32>, k: i32) -> i64 {
        happiness.sort_unstable_by(|a, b| b.cmp(a));

        let mut ans: i64 = 0;
        for i in 0..(k as usize) {
            let x = happiness[i] as i64 - i as i64;
            if x > 0 {
                ans += x;
            }
        }
        ans
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Sorting Approach

Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) due to the input list.

Hash Map Approach

Time Complexity: O(n)
Space Complexity: O(n) for the dictionary used as a hash map.

Greedy + Sorting–

Complexity analysis

ApproachTimeSpaceWhen to Use
Sorting + GreedyO(n log n)O(1)General case. Simple and most commonly expected interview solution.
Hash Map CountingO(n + U log U)O(U)When many duplicate happiness values exist and you want to process unique values.

Frequently asked questions

Is Maximize Happiness of Selected Children easy or hard?

Maximize Happiness of Selected Children is categorized as a Medium difficulty problem. The challenge lies in recognizing the greedy pattern: picking the largest happiness values first minimizes the penalty applied to them.

Maximize Happiness of Selected Children Python/Java solution

In Python or Java, sort the happiness array in descending order and iterate for k selections. Add max(happiness[i] - i, 0) to the result at each step. Stop early if the value becomes zero or negative. This implementation is concise and runs in O(n log n) time.

How to solve Maximize Happiness of Selected Children in O(n)?

A near-linear solution can be achieved by counting frequencies of happiness values using a hash map and processing unique values in descending order. This avoids sorting every element and works in O(n + U log U) where U is the number of unique values. The greedy rule remains the same: always pick the highest remaining happiness value.

What is the best approach for Maximize Happiness of Selected Children?

The most effective approach is a greedy strategy combined with sorting. Sort the happiness array in descending order and pick the top k values while subtracting the number of already selected children from each value. The contribution becomes max(happiness[i] - i, 0). This method runs in O(n log n) time and uses constant extra space.

Is Maximize Happiness of Selected Children asked at Google/Amazon/Meta?

Greedy array optimization problems similar to this frequently appear in interviews at companies like Amazon, Google, and Meta. The problem tests your ability to recognize a greedy ordering strategy and reason about how repeated operations affect future values.

What data structure is used in Maximize Happiness of Selected Children?

The primary data structures are arrays and sorting utilities. The optimized solution sorts the array and iterates through it greedily. An alternative implementation uses a hash map to count frequencies of happiness values before processing them in descending order.

What is the time complexity of Maximize Happiness of Selected Children?

The optimal solution runs in O(n log n) time due to sorting the happiness array. After sorting, a single pass over at most k elements computes the total happiness. Space complexity is O(1) if the sorting algorithm is in-place.

Comments

Now write it yourselfClose this page and solve Maximize Happiness of Selected Children in the editor, without looking.
Practise Maximize Happiness of Selected Children