Max Min Discussions | Algorithms | HackerRank
  • + 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;
    }