Advertisement
mickypinata

PROG-T1005: Max Sequence

Dec 5th, 2020
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 2500;
  5.  
  6. int arr[N + 1], dp[N + 1], par[N + 1];
  7. int nSeq;
  8.  
  9. int main(){
  10.  
  11.     scanf("%d", &nSeq);
  12.     for(int i = 1; i <=  nSeq; ++i){
  13.         scanf("%d", &arr[i]);
  14.     }
  15.  
  16.     int bestIdx = 0;
  17.     int ans = -1e9;
  18.     for(int i = nSeq; i >= 1; --i){
  19.         if(arr[i] > arr[i] + dp[i + 1]){
  20.             dp[i] = arr[i];
  21.             par[i] = i;
  22.         } else {
  23.             dp[i] = arr[i] + dp[i + 1];
  24.             par[i] = i + 1;
  25.         }
  26.         if(dp[i] > ans){
  27.             ans = dp[i];
  28.             bestIdx = i;
  29.         }
  30.     }
  31.  
  32.     if(ans <= 0){
  33.         cout << "Empty sequence";
  34.     } else {
  35.         int i = bestIdx;
  36.         cout << arr[i] << " ";
  37.         while(par[i] != i){
  38.             i = par[i];
  39.             cout << arr[i] << " ";
  40.         }
  41.         cout << "\n" << ans;
  42.     }
  43.  
  44.     return 0;
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement