fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. typedef long long ll;
  8.  
  9. int main() {
  10. // Fast I/O
  11. ios_base::sync_with_stdio(false);
  12. cin.tie(NULL);
  13.  
  14. int n;
  15. if (!(cin >> n)) return 0;
  16.  
  17. vector<int> arr(n);
  18. for (int i = 0; i < n; i++) {
  19. cin >> arr[i];
  20. }
  21.  
  22. int k;
  23. cin >> k;
  24.  
  25. // Step 1: Sort in descending order to pick the largest happiness first
  26. sort(arr.rbegin(), arr.rend());
  27.  
  28. ll totalHappiness = 0;
  29.  
  30. // Step 2: Select top k children while accounting for the turn penalty
  31. for (int i = 0; i < k; i++) {
  32. ll effectiveHappiness = arr[i] - i;
  33.  
  34. // If effective happiness becomes 0 or negative, remaining items won't add any value
  35. if (effectiveHappiness <= 0) {
  36. break;
  37. }
  38.  
  39. totalHappiness += effectiveHappiness;
  40. }
  41.  
  42. cout << "Maximum Happiness : " << totalHappiness << "\n";
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0s 5320KB
stdin
5
1
2
3
4
5
2
stdout
Maximum Happiness : 8