fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. int max_happy(vector<int>happy,int k){
  6. int n=happy.size();
  7. sort(happy.begin(),happy.end());
  8. int happiness=0;
  9. for(int i=n-1;i>=n-k;i--){
  10. happiness+=happy[i];
  11. }
  12. return happiness;
  13. }
  14. int main(){
  15. int n;
  16. cin>>n;
  17. vector<int>happy(n);
  18. for(int i=0;i<n;i++){
  19. cin>>happy[i];
  20. }
  21.  
  22. int k;
  23. cin>>k;
  24. int ans;
  25. ans=max_happy(happy,k);
  26. cout<<"Maximum happiness from the given vector is: "<<ans<<endl;
  27. return 0;
  28. }
Success #stdin #stdout 0s 5324KB
stdin
7
3 4 2 7 8 9 10
3
stdout
Maximum happiness from the given vector is: 27