Easy Java Solution | Detailed Approach
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involves maximizing the sum of happiness by selecting elements from an arra
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves maximizing the sum of happiness by selecting elements from an array within a limited selection constraint. One intuitive approach could be to sort the array and then greedily select the top \'k\' elements that contribute positively to the happiness sum.\n\n---\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSort the \'happiness\' array in ascending order.\nInitialize variables sum to store the total happiness sum and count to keep track of the number of elements selected.\nIterate over the last \'k\' elements of the sorted array.\nFor each element, check if selecting it would result in a positive increase in happiness (i.e., if the difference between the element\'s happiness and count is positive).\nIf positive, add this difference to sum, increment count by 1, and continue to the next iteration.\nOnce \'k\' elements are selected or no more elements meet the condition for selection, return the total sum of happiness (sum).\n\n---\n\n\n# Complexity\n\nTime complexity:\n<!-- Add your time complexity here, e.g. $$O(n \\log n)$$ --> \nThe time complexity is O(n log n) due to the sorting step, where \'n\' is the length of the happiness array.\n\nSpace complexity:\n<!-- Add your space complexity here, e.g. $$O(1)$$ --> \nThe space complexity is O(1) since only a constant amount of extra space is used regardless of the size of the input array.\n# Code\n```java []\nclass Solution {\n    public long maximumHappinessSum(int[] happiness, int k) {\n        long sum = 0;\n        int count = 0;\n        int n = happiness.length;\n        Arrays.sort(happiness);\n        for(int i=0;i<k;i++){\n            if(happiness[n-1-i]-count>0){\n                sum += happiness[n-1-i]-count;\n                count++;\n            }\n        }\n        return sum;\n    }\n}\n```\n\n\n
['Array', 'Greedy', 'Sorting', 'Java']