Max Min Discussions | Algorithms | HackerRank

Sort by

recency

|

885 Discussions

|

  • + 0 comments

    Here's my Java 8 solution, passing all tests, for Max Score of 35:

    Code is fairly simple & self-explanatory. First sort the List. Then iterate through it once, doing a "sliding sublist window", calculate Current Diff by considering the first / last element of the sub-list as Min / Max, and compare that with the "Overall Min Diff" & update as needed.

    `

    public static int maxMin(int k, List<Integer> arr) {
        // Write your code here
        int minUnfairness = Integer.MAX_VALUE;
    
        Collections.sort(arr);
    
        for (int i = 0 ; i <= (arr.size() - k) ; i++) {
            List<Integer> curSubLst = arr.subList(i, (i + k));
            int curUnfairness = curSubLst.get(curSubLst.size() - 1) - curSubLst.get(0);
            minUnfairness = Math.min(minUnfairness, curUnfairness);
        }
    
        return minUnfairness;
    }
    

    `

    This problem's solution approach is very similar / identical to the "Minimum Absolute Difference in an Array" problem: as explained in this comment I have posted in the discussions of that problem.

  • + 0 comments

    Here is my Python solution!

    def maxMin(k, arr):
        arr.sort()
        unfairness = arr[k - 1] - arr[0]
        for i in range(1, len(arr) - k + 1):
            unfairness = min(arr[k + i - 1] - arr[i], unfairness)
        return unfairness
    
  • + 0 comments

    Java:

    public static int maxMin(int k, List arr) {

        int[] arr2 = arr.stream().mapToInt(i -> i).toArray();
    
        //primitive arrays are faster
    
        Arrays.sort(arr2);
    
        int diff = Integer.MAX_VALUE;
    
        for (int j=0; j < arr2.length - k + 1; ++j) {
    
            if (arr2[j+k-1] - arr2[j] < diff) {
    
                diff = arr2[j+k-1] - arr2[j];
    
            }
    
        }
        return diff;
    }
    
  • + 0 comments

    def maxMin(k, arr): return min(map(lambda x, y: abs(x - y), sorted(arr)[:-k + 1], sorted(arr)[k - 1:]))

  • + 0 comments

    JS

    function maxMin(k, arr) {
      // sort - lowest to highest
      arr.sort((a, b) => a - b);
    
      // calculate unfairness of "first chunk" of size k
      let minUnfairness = arr[k - 1] - arr[0];
    
      for (let i = 1; i + k - 1 < arr.length; i++) {
        // calculate unfairness in "next chunk" of size k
        const unfairness = arr[i + k - 1] - arr[i];
    
        if (unfairness < minUnfairness) {
          minUnfairness = unfairness;
        }
      }
    
      return minUnfairness;
    }