-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_search_forest.cpp
53 lines (48 loc) · 1.06 KB
/
Binary_search_forest.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Question link - https://practice.geeksforgeeks.org/problems/ffd66b6a0bf7cefb9987fa455974b6ea5695709e/1/
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
int find_height(int tree[], int n, int k)
{
sort(tree,tree+n);
int i=0,j=tree[n-1];
while(i<=j)
{
int mid=i+(j-i)/2;
int sum=0;
for(int l=n-1;l>=0;l--)
{
if(tree[l]-mid<0)
break;
sum+=tree[l]-mid;
}
if(sum==k)
return mid;
else if(sum>k)
i=mid+1;
else
j=mid-1;
}
return -1;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int n,k;
cin>>n;
int tree[n];
for(int i=0; i<n; i++)
cin>>tree[i];
cin>>k;
Solution ob;
cout<< ob.find_height(tree,n,k) << endl;
}
return 1;
} // } Driver Code Ends