fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int maxTwoNonOverlappingSubarraysSum(const vector<int>& nums) {
  4. int n = nums.size() - 1;
  5. if (n <= 0) return 0;
  6.  
  7. vector<int> leftBest(n + 2, 0);
  8. vector<int> rightBest(n + 2, 0);
  9.  
  10. // Single pass left-to-right (Kadane + Running Max merged)
  11. int currMax = 0;
  12. int globalMax = INT_MIN;
  13. for (int i = 1; i <= n; ++i) {
  14. currMax = max(nums[i], currMax + nums[i]);
  15. globalMax = max(globalMax, currMax);
  16. leftBest[i] = globalMax;
  17. }
  18.  
  19. // Single pass right-to-left
  20. currMax = 0;
  21. globalMax = INT_MIN;
  22. for (int i = n; i >= 1; --i) {
  23. currMax = max(nums[i], currMax + nums[i]);
  24. globalMax = max(globalMax, currMax);
  25. rightBest[i] = globalMax;
  26. }
  27.  
  28. // Find optimal split point
  29. int result = 0;
  30. for (int i = 1; i < n; ++i) {
  31. result = max(result, leftBest[i] + rightBest[i + 1]);
  32. }
  33.  
  34. return result;
  35. }
  36. int main(){
  37. int n;
  38. cin>>n;
  39. vector<int>a(n+1);
  40. for(int i = 1 ; i<= n;i++){
  41. cin>>a[i];
  42. }
  43. cout<<maxTwoNonOverlappingSubarraysSum(a);
  44. }
Success #stdin #stdout 0s 5308KB
stdin
7
1
5
-3
4
-9
9
2
stdout
18