fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <climits>
  5.  
  6. using namespace std;
  7.  
  8. int find_best_sum_subarray(int n, const vector<int>& b, int k) {
  9. vector<int> p(n, 0);
  10.  
  11. // Compute prefix sums
  12. p[0] = b[0];
  13. for (int i = 1; i < n; ++i) {
  14. p[i] = b[i] + p[i - 1];
  15. }
  16.  
  17. int final_ans = INT_MIN;
  18.  
  19. // Find the best sum subarray ending at each index j with size <= k
  20. for (int j = 0; j < n; ++j) {
  21. int r = INT_MIN;
  22. for (int l = j; l >= max(0, j - k + 1); --l) {
  23. int sum_subarray = p[j] - (l > 0 ? p[l - 1] : 0);
  24. r = max(r, sum_subarray);
  25. }
  26. final_ans = max(final_ans, r);
  27. }
  28.  
  29. return final_ans;
  30. }
  31.  
  32. int main() {
  33. int n = 6; // Example value for n
  34. vector<int> b = {-1, -3, 4, 3, -2, 2}; // 0-based input array
  35. int k = 4; // Example value for k
  36. int result = find_best_sum_subarray(n, b, k);
  37. cout << result << endl; // Output the result
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0.01s 5296KB
stdin
Standard input is empty
stdout
7