Max Min Discussions | | HackerRank

Max Min

Sort by

recency

|

185 Discussions

|

  • + 0 comments

    Java solution:

        public static int maxMin(int k, List<Integer> arr) {
        // Write your code here
            arr.sort(Comparator.naturalOrder());
            int result = Integer.MAX_VALUE;
            for (int i = 0; i <= arr.size() - k; i++) {
                result = Math.min(result, arr.get(i + k - 1) - arr.get(i)); 
            }
            return result;
        }
    
  • + 0 comments

    Kotlin Solution

    fun maxMin(k: Int, arr: Array<Int>): Int {
        arr.sort()
        return (0..arr.size - k).minOf { i -> arr[i + k - 1] - arr[i] }
    }
    
  • + 0 comments

    c++

    int maxMin(int k, vector<int> arr) {
        int res = INT_MAX;
        std::sort(arr.begin(), arr.end());
        for(int i = 0; i + k -1 < arr.size(); ++i){
            res = std::min(res, arr[i+k-1] - arr[i]);
        }
        return res;
    }
    
  • + 0 comments

    short answer no need to loop. just sort input and pickup max-min is result. but instruction is test all pairs and it's need loop to follow instuction.

  • + 0 comments

    short c++ solution

    #define all(a) (a).begin(), (a).end()
    
    int maxMin(int k, vector<int> arr) {
        sort(all(arr));
        
        int n = arr.size();
        int best = 1e9;
        for (int i = 0; i <= n-k; i++) {
            best = min(best, arr[k-1+i]-arr[i]);
        }
        return best;
    }