Advertisement
ann8497

kth max in array

Feb 8th, 2023
1,354
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.60 KB | None | 0 0
  1. // https://leetcode.com/discuss/interview-question/1527195/Google-Interview-Questions
  2.  
  3. #include <iostream>
  4. #include <bits/stdc++.h>
  5. typedef long long ll;
  6. using namespace std;
  7.  
  8. int main()
  9. {  
  10.     int n; cin>>n;
  11.     vector<int>v(n);
  12.     for(int i=0;i<n;i++) cin>>v[i];
  13.     int k; cin>>k;
  14.     int l=0, r=n-1;
  15.     int cnt = n-k+1, p = 0, ans = -1;
  16.     while(l<=r){
  17.         if(abs(v[r]) > abs(v[l])){
  18.             ans=v[r];
  19.             r--;
  20.         }
  21.         else{
  22.             ans=v[l];
  23.             l++;
  24.         }
  25.         p++;
  26.         if(p==cnt) break;
  27.     }
  28.     cout<<ans;
  29.     return 0;
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement