Max Min

HackerRank 問題: Max Min

Question

You will be given a list of integers, arr , and a single integer k . You must create an array of length k from elements of arr such that its unfairness is minimized. Call that array arr'. Unfairness of an array is calculated as max(arr') - min(arr')

Where:

  • max denotes the largest integer in arr'
  • min denotes the smallest integer in arr'

HackerRank 問題: Max Min

Answer

<?php

/*
 * Complete the 'maxMin' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts following parameters:
 *  1. INTEGER k
 *  2. INTEGER_ARRAY arr
 */

function maxMin($select_element_number, $number_list) {
    // sort number
    sort($number_list);
    $length_of_number_list = count($number_list);
    // get check end index
    $final_check_index = $length_of_number_list - $select_element_number;


    // find minimum unfairness
    $minimum_unfairness = 1000000001;
    for ($check_index = 0; $check_index <= $final_check_index; $check_index++) {
        // find continuous number diff number
        $min_number = $number_list[$check_index];
        $max_number = $number_list[$check_index + $select_element_number - 1];
        $diff_number = $max_number - $min_number;

        if ($diff_number < $minimum_unfairness) {
            // find smaller unfairness
            $minimum_unfairness = $diff_number;
        }
    }

    return $minimum_unfairness;
}

$fptr = fopen(getenv("OUTPUT_PATH"), "w");

$n = intval(trim(fgets(STDIN)));

$k = intval(trim(fgets(STDIN)));

$arr = array();

for ($i = 0; $i < $n; $i++) {
    $arr_item = intval(trim(fgets(STDIN)));
    $arr[] = $arr_item;
}

$result = maxMin($k, $arr);

fwrite($fptr, $result . "\n");

fclose($fptr);

Reference