Code without using binary search


#1

int Solution::solve(vector &a, int b)
{
sort(a.begin(),a.end(),greater());
int n=a.size(),f=0;
long long int s=0,e=0,remaining=b,ans=0;double ele=0;
for(int i=1;i<n;i++)
{
// cout<<a[i]<<" “<<a[i-1]<<”\n";
e=a[i];

    remaining-=(a[i-1]-a[i])*i;
    // cout<<remaining<<"\n";
    ele=remaining/i;
    if(remaining<0)
    {   
        remaining+=(a[i-1]-a[i])*i;
        ele=remaining/double(i);
        // cout<<ele<<" "<<remaining<<" "<<i<<"\n";
        f=0;
        ans=a[i-1];
        break;
    }
    else if(remaining ==0)
    {
        return a[i];
        
    }
    
}

//f==0 when 
if(f==0)
{
    // cout<<"k";
    // cout<<"ele:"<<ele<<"\n";
    // for(long long int i=0;i<=e;i++)
    // {
    //     if(i>=ele)
    //         return ans-i;
        
    // }
    return ans-ceil(ele);
    
    
}
else // f==1 when all n trees are equal in height of the last tree
{
    // for(long long int i=0;i<=a[n-1];i++)
    // {
    //     if (i>=ele)
    //         return a[n-1]-i;            
    // }
    return a[n-1]-ceil(ele);
}

//means now all trees are of same
// if(f==0)
return 0;

}


#2

Simple version of that

int Solution::solve(vector &A, int B) {
sort(A.begin(),A.end(),greater());
int wood=0;
for(int i=1;i<A.size();i++){
int add = (A[i-1]-A[i]);
int req = B-wood;
req = (req%i==0) ? req/i : (req/i)+1;
if(add >= req){
return A[i-1]-req;
}
else{
wood+=i*add;
}
}
return A[-1];
}