Time limit exceeds


#1

The solution is not yet provided so I can not cross check. However, the time limit exceeds for an n*log n solution written in java. Is it possible in better time?


#2

Accepted cpp O(n*logn) :

int Solution::solve(vector<int> &ar, int m) {
    sort(ar.begin(),ar.end());
    int n = ar.size();
    if(n < m)
        return 0;
        int ans = INT_MAX;
        for(int i=m-1;i<n;i++)
        {
            ans = min(ans,ar[i] - ar[i-m+1]);
        }
       return ans;
}

Accepted Java 8 (Array support) O(n*logn):

public class Solution {
    public int solve(int[] A, int B) {
        Arrays.sort(A);
        int n = A.length;
        if(n < B || B == 0)
            return 0;
        int ans = Integer.MAX_VALUE;
        for(int i=B-1;i<n;i++)
        {
            ans = Math.min(ans,A[i]-A[i-B+1]);
        }
        return ans;
    }
}