easy to understand || Beginer friendly || Fastest (100%) || Short & Concise
Intuition\nThe intuition behind the provided code seems to be finding the maximum possible sum of happiness that can be achieved by selecting a certain number o
# Intuition\nThe intuition behind the provided code seems to be finding the maximum possible sum of happiness that can be achieved by selecting a certain number of participants under given constraints.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1)Sorting the happiness vector: The function sorts the happiness vector in non-increasing order using std::sort with greater<int>(). This step ensures that the highest happiness values come first.\n\n2)Handling the case when k is 1: If k is equal to 1, the function selects the highest happiness value and returns it. This is done to handle the special case when only one participant can be chosen.\n\n3)Iterating through the sorted happiness vector: After handling the case when k is 1, the function iterates through the sorted happiness vector while there are still participants (k > 0) and updates the total happiness sum a.\n\n4)Calculating the contribution of each participant: For each participant, the function calculates their contribution to the total happiness sum. The contribution of the current participant (happiness[i]) is decreased by s, which represents the number of previously selected participants.\n\n5)Updating the total happiness sum and indices: The function updates the total happiness sum a by adding the contribution of the current participant (happiness[i] - s). It also increments i to move to the next participant, decrements k to track the remaining participants to be selected, and increments s to account for the selected participant.\n\n6)Returning the total happiness sum: Finally, the function returns the total happiness sum a, which represents the maximum sum of happiness that can be achieved by selecting k participants following the given rules.\n\n# Complexity\n- Time complexity:\n O(n log n) \n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n    long long maximumHappinessSum(vector<int>& happiness, int k) {\n        long long a=0;\n        int n=happiness.size();\n        sort(happiness.begin(),happiness.end(),greater<int>());\n        int i=0;\n        if(k==1)\n        {\n            a+=happiness[i];\n            return a;\n        }\n        int s = 0;\n        while(k>0)\n        {\n            if(happiness[i]-s<=0)\n            {\n                \n                return a;\n            }\n            a+= happiness[i]-s;\n            i++;\n            k--;\n            s++;\n            \n        }\n        return a;\n    }\n};\n```
['Array', 'Sorting', 'C++']