fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. int main() {
  8. vector<int> pnl = {4, 3, -2, 9, -4, 2,7};
  9. int n = pnl.size();
  10. int k = 6;
  11.  
  12. // p[i] stores the sum of the first i elements
  13. vector<long long> p(n + 1, 0);
  14. for (int i = 0; i < n; i++) {
  15. p[i + 1] = p[i] + pnl[i];
  16. }
  17.  
  18. long long maxi = -1e18;
  19.  
  20. // Subarray ending at index i (1-based index in prefix array: 1 to n)
  21. for (int i = 1; i <= n; i++) {
  22. // j is the start boundary: subarray length is (i - j), which is <= k
  23. for (int j = max(0, i - k); j < i; j++) {
  24. long long sum = p[i] - p[j];
  25. maxi = max(maxi, sum);
  26. }
  27. }
  28.  
  29. cout << maxi << "\n";
  30. return 0;
  31. }
Success #stdin #stdout 0s 5324KB
stdin
Standard input is empty
stdout
15