Simple C++ Soln - O(nlogn) time & O(1) space


#1
int Solution::solve(vector<int> &a, int b) {
    int n=a.size();
    sort(a.rbegin(), a.rend());
    int cur=1, res=0;
    for(int i=0;i<n;i++)
    {
        int x=(a[i]-ceil((float)(b-res)/(float)cur));
        if(i==n-1){
            if(x<0) return -1;
            return x;
        }
        else if(x<a[i+1]){
            res+=(cur*(a[i]-a[i+1]));
            cur++;
        }
        else{
            return x;
        }
    }
    return -1;
}