fork download
  1. //
  2. // main.cpp
  3. // Sliding Window
  4. //
  5. // Created by Himanshu on 18/09/21.
  6. //
  7.  
  8.  
  9. #include <iostream>
  10. #include <climits>
  11. using namespace std;
  12. const int N = 7;
  13.  
  14. int solve (int A[], int k) {
  15.  
  16. int maxSum = INT_MIN, currSum = 0;
  17.  
  18. for (int i=0; i<k; i++) {
  19. currSum += A[i];
  20. }
  21.  
  22. maxSum = max(maxSum, currSum);
  23. for (int i=k; i<N; i++) {
  24. currSum += A[i] - A[i-k];
  25. maxSum = max(maxSum, currSum);
  26. }
  27.  
  28. return maxSum;
  29. }
  30.  
  31. int main() {
  32. int A[N] = {5, 3, 4, 6, 8, 11, 20};
  33. int k = 7;
  34.  
  35. cout<<"Maximum subset sum: "<<solve(A, k)<<endl;
  36.  
  37. k = 4;
  38. cout<<"Maximum subset sum: "<<solve(A, k)<<endl;
  39.  
  40. }
  41.  
Success #stdin #stdout 0s 5548KB
stdin
Standard input is empty
stdout
Maximum subset sum: 57
Maximum subset sum: 45