Easy C++ Sorting Solution | Beats 100 ✅💯
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involves selecting elements from the array to maximize the sum of happiness
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves selecting elements from the array to maximize the sum of happiness while adhering to the constraint of selecting at most k elements. To maximize the sum, it\'s intuitive to start by selecting the elements with the highest happiness values.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sort the happiness array in non-decreasing order.\n2. Reverse the sorted array to have the elements in non-increasing order (highest happiness values first).\n3. Initialize a variable count to keep track of the number of elements selected.\n4. Initialize a variable ans to keep track of the sum of happiness.\nIterate through the sorted array:\n5. Subtract the current count from the happiness value of the current element.\n6. If the resulting happiness value is positive, increment count, add the adjusted happiness value to ans, and continue.\n7. If the resulting happiness value is non-positive, break the loop.\n8. If count reaches k, break the loop.\n9. Return the final value of ans as the maximum happiness sum.\n# Complexity\n- Time complexity: O(nlogn) \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 {\npublic:\n    long long maximumHappinessSum(vector<int>& happiness, int k) {\n         int count=0;\n        sort(happiness.begin(),happiness.end());\n        reverse(happiness.begin(),happiness.end());\n        long long ans=0;\n        for(int i=0;i<happiness.size();i++){\n            happiness[i]-=count;\n            if(happiness[i]>0){\n                count++;\n                ans+=happiness[i];\n            }\n            else break;\n            if(count==k)break;\n        }\n        return ans;\n    }\n};\n```
['C++']