nrk009

Maximum Contigous Array

Feb 22nd, 2020
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1.  
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5. #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL)
  6. #define ll long long
  7. #define ld long double
  8. #define pb push_back
  9. #define fe first
  10. #define se second
  11. #define nl "\n"
  12. #define pp pair < ll , ll >
  13. #define sz(x) (ll)x.size()
  14. #define st(x) sort(x.begin(),x.end())
  15. #define rst(x) sort(x.rbegin(), x.rend())
  16. #define all(x) x.begin(),x.end()
  17. long double pi = 3.14159265358979323;
  18.  
  19. const double EPS = 1e-12;
  20. const int N = 1e6 + 5;
  21. const int mod = 1e9 + 7;
  22.  
  23. //MaximumContigousSubarray
  24.  
  25.  
  26. int main()
  27. {
  28.     fast;
  29.     ll n;
  30.     cin >> n ;
  31.     ll a[n];
  32.     for(int i = 0 ; i < n ;i++ ){
  33.         cin >> a[i];      
  34.     }
  35.  
  36.    /* ll dp[n];
  37.     dp[0] = a[0];
  38.     for(int i = 1 ; i < n ; i++ ){
  39.       dp[i] = max(dp[i-1] + a[i] , a[i]);
  40.     }
  41.  
  42.     cout << *max_element(dp , dp + n);*/
  43.     //Space Complexity O(n)
  44.  
  45.     ll ans = a[0];
  46.  
  47.     ll prevmax = 0;
  48.     int prevind = 0 , currind = 0 ;
  49.     for(int i = 0 ; i < n ; i++ ){
  50.      /* if(ans < max(a[i] , a[i] + prevmax)){
  51.        
  52.         if(prevmax + a[i] >= a[i]){
  53.           currind = i;
  54.         }
  55.         else{
  56.           prevind = currind = i;
  57.         }
  58.        
  59.       }*/
  60.  
  61.         ans = max({ans ,a[i] , a[i] + prevmax});
  62.         prevmax = max(a[i] , prevmax + a[i]);
  63.       }
  64.     //}
  65.     //cout << prevind << " " << currind << "\n";
  66.     cout << ans;
  67.     //Printing indexes also
  68.     //Space complexity O(1);
  69.      
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
  91.    
  92.     return 0;
  93.    
  94. }
Add Comment
Please, Sign In to add comment