fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int MAXN = 1000001;
  6. const long long INF = 1e18;
  7.  
  8. int n, a[MAXN];
  9. long long prefSum[MAXN], prefMin[MAXN], ans = -INF;
  10.  
  11. int main() {
  12. cin >> n;
  13. for (int i = 1; i <= n; i++) cin >> a[i];
  14.  
  15. // Initializing prefix sum and prefix minimum
  16. prefSum[0] = prefMin[0] = 0;
  17.  
  18. // Compute prefix sums and prefix minimums
  19. for (int i = 1; i <= n; i++) {
  20. prefSum[i] = prefSum[i - 1] + a[i];
  21. prefMin[i] = min(prefMin[i - 1], prefSum[i]); // Store minimum prefix sum
  22. }
  23.  
  24. // Finding the maximum subarray sum
  25. for (int i = 1; i <= n; i++) {
  26. ans = max(ans, prefSum[i] - prefMin[i - 1]);
  27. // Maximum sum is found by subtracting the smallest prefix sum from the current prefix sum
  28. }
  29.  
  30. cout << ans;
  31. }
  32.  
Success #stdin #stdout 0.01s 7812KB
stdin
5
1 -3 2 4 -2
stdout
6