fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. long helper(vector<int>&nums, int k) {
  5. multiset<long> st;
  6.  
  7. long sum=0l, res=LONG_MIN;
  8. for(int j=0; j<nums.size(); j++) {
  9. sum+=nums[j];
  10. st.insert(nums[j]);
  11. if(j<k-1) continue;
  12. while(st.size()>k) {
  13. sum-=*st.begin();
  14. st.erase(st.begin());
  15. }
  16. res=max(res, sum);
  17. }
  18.  
  19. return res;
  20. }
  21.  
  22. long solution(vector<int>&nums, int k){
  23. long res1=helper(nums, k);
  24.  
  25. reverse(begin(nums), end(nums));
  26. long res2=helper(nums, k);
  27.  
  28. return max(res1, res2);
  29. }
  30.  
  31. int main() {
  32. vector<int> nums={-5,4,-10,-1,-5,8,-3};
  33. cout<<solution(nums, 3)<<endl;
  34.  
  35. nums={4,4,4,4,4};
  36. cout<<solution(nums, 4)<<endl;
  37.  
  38. return 0;
  39. }
  40.  
  41.  
Success #stdin #stdout 0.01s 5528KB
stdin
Standard input is empty
stdout
11
16