fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long int
  4. #define double long double
  5. inline int power(int a, int b) {
  6. int x = 1;
  7. while (b) {
  8. if (b & 1) x *= a;
  9. a *= a;
  10. b >>= 1;
  11. }
  12. return x;
  13. }
  14.  
  15.  
  16. const int M = 1000000007;
  17. const int N = 3e5+9;
  18. const int INF = 2e9+1;
  19. const int LINF = 2000000000000000001;
  20.  
  21. //_ ***************************** START Below *******************************
  22.  
  23.  
  24.  
  25. vector<int> a;
  26. void consistency(int n) {
  27.  
  28. vector<int> prefixMax(n+1, 0);
  29. vector<int> sufixMax(n+1, 0);
  30.  
  31. //* Kadane => P[R] = max(P[R-1] + a[R], a[R] , 0 )
  32. //* curr = max(prev+a[i], a[i], 0)
  33. int prev = 0;
  34. int maxi = 0;
  35. for(int i=0; i<n; i++){
  36. int curr = max(prev+a[i], a[i]);
  37. curr = max(curr, 0LL);
  38. prev = curr;
  39. maxi = max(maxi, curr);
  40. prefixMax[i] = maxi;
  41. }
  42.  
  43. int next = 0;
  44. maxi = 0;
  45. for(int i=n-1; i>=0; i--){
  46. int curr = max(next+a[i], a[i]);
  47. curr = max(curr, 0LL);
  48. next = curr;
  49. maxi = max(maxi, curr);
  50. sufixMax[i] = maxi;
  51. }
  52.  
  53. maxi = 0;
  54. for(int i=0; i<n-1; i++){
  55. maxi = max(maxi, prefixMax[i] + sufixMax[i+1]);
  56. }
  57.  
  58. cout << maxi << endl;
  59.  
  60. }
  61.  
  62. void solve() {
  63.  
  64. int n;
  65. cin >> n;
  66. a.resize(n);
  67. for(int i=0; i<n; i++) cin >> a[i];
  68. consistency(n) ;
  69.  
  70. }
  71.  
  72.  
  73.  
  74.  
  75.  
  76. int32_t main() {
  77. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  78.  
  79. int t = 1;
  80. while (t--) {
  81. solve();
  82. }
  83.  
  84. return 0;
  85. }
Success #stdin #stdout 0s 5320KB
stdin
7
1 5 -3 4 -9 9 2
stdout
18