Java Solution | Easy to Understand | Beginner Friendly
Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind this algorithm is to select the children with higher happiness val
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this algorithm is to select the children with higher happiness values first to maximize the sum. The algorithm iterates through the sorted array of happiness values in descending order, selecting children and decrementing the happiness of the remaining unselected children in each turn.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1) Sort the array of happiness values in ascending order.\n\n2) Initialize a variable j to point to the last element of the sorted array.\n\n3) Initialize variables cnt and ans to keep track of the count of selected children and the maximum sum of happiness values, respectively.\n\n4) Iterate through the sorted array from the end, selecting children and updating the ans until either all k children are selected or the remaining happiness becomes non-positive.\n\n5) Return the final ans.\n\n# Complexity\n- Time complexity: **O(n log n)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n    public long maximumHappinessSum(int[] happiness, int k) {\n        int len = happiness.length;\n        int j = len - 1;\n        if (k <= 0)\n            return 0;\n        Arrays.sort(happiness);\n        int cnt = 0;\n        long ans = 0;\n        while (j >= 0 && k > 0) {\n            if (happiness[j] - cnt <= 0)\n                break;\n            ans += (happiness[j] - cnt);\n            cnt++;\n            j--;\n            k--;\n        }\n        return ans;\n    }\n}\n```
['Array', 'Sorting', 'Java']