Max Min Discussions | Algorithms | HackerRank

Sort by

recency

|

879 Discussions

|

  • + 0 comments

    Two pointer approach

    def maxMin(k, arr):
        # Write your code here
        arr.sort()
        unfairness = []
        p1 = 0
        p2 = k - 1
        
        while p2 < len(arr):
            unfairness.append(arr[p2] - arr[p1])
            p1 += 1
            p2 += 1
        return min(unfairness)
        ****
    
  • + 0 comments
    def maxMin(k, arr):
        # Write your code here
        n = len(arr)
        arr.sort()
        res=[]
        for i in range(n-k+1):
            uf=arr[i+k-1] - arr[i]
            print(uf)
            res.append(uf)
        return min(res)
    
  • + 0 comments

    `java public static int maxMin(int k, List arr) { // Write your code here // Sorting and Sliding Window Collections.sort(arr); int min = 0; int end = 0; int start = 0; int minUnfairness = Integer.MAX_VALUE; while(end < arr.size()) { if((end-start)+1 < k) { end++; }else { int currentUnfairness = arr.get(end) - arr.get(start); minUnfairness = Math.min(minUnfairness, currentUnfairness); start++; } } return minUnfairness; }

    `

  • + 0 comments

    Java

    public static int maxMin(int k, List<Integer> arr) {
        Collections.sort(arr);
        int min =Integer.MAX_VALUE;
        int cal;
        List<Integer> list;
        for(int i=0;i<=arr.size()-k;i++){
            list=arr.subList(i, i+k);
            cal=list.get(list.size()-1)-list.get(0);
            if(cal<min){
                min=cal;
              if(min==0){
                  return 0;
              }
            }
        }
        return min;
    }
    
  • + 0 comments
    def maxMin(k, arr):
        arr.sort()
        unfairness = set()
        for i in range(len(arr)-k+1):
            unfairness.add(arr[i+k-1] - arr[i])
        return sorted(list(unfairness))[0]