Advertisement
Guest User

CF Maximum Difference Problem

a guest
Aug 8th, 2021
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int main() {
  6.     int n; cin >> n; // size of array
  7.     vector<int> a(n);
  8.     for (int i = 0; i < n; i++) cin >> a[i]; // read array
  9.     vector<int> candidates;
  10.     int ans = 0;
  11.     for (int j = 0; j < n; j++) {
  12.         // if the index is a potential answer, add it
  13.         if (candidates.size()==0 || a[j]<a[candidates.back()]) candidates.push_back(j);
  14.         // start the binary search, notice that candidates[candidates.size()-1] always works
  15.         int l=0, r=candidates.size()-2, i=candidates[candidates.size()-1];
  16.         while (l <= r) {
  17.             int m = (l+r)/2;
  18.             if (a[candidates[m]] <= a[j]) {
  19.                 i = candidates[m];
  20.                 r = m-1;
  21.             } else l = m+1;
  22.         }
  23.         // take the maximum result of the binary search
  24.         ans = max(ans, j-i);
  25.     }
  26.     cout << ans << endl;
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement