Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
Usporiadaj zadané prvky vzostupne. Vytvor k
častí poľa. Vypočítaj unfairness
ako rozdiel medzi prvým a posledným prvkom pre všetky vytvorené časti. Nájdi minimum zpomedzi všetkých unfairness
.
Problém je známy aj pod menom Angry Children.
Vytvoril som riešenie v týchto programovacích jazykoch:
Všetky riešenia sú dostupné aj na mojom GitHub profile.
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 |
n = gets.to_i k = gets.to_i candy = Array.new(n) for i in 0..n-1 candy[i] = gets.to_i end candy.sort! {|l,j| l <=> j} unfairness = candy[candy.length - 1] for i in 0..candy.length - k do temp_unfairness = candy[i + k - 1] - candy[i] unfairness = temp_unfairness if unfairness > temp_unfairness end puts unfairness |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.*; public class MaxMin { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = Integer.parseInt(stdin.nextLine()); int k = Integer.parseInt(stdin.nextLine()); int[] candies = new int[tests]; for(int i = 0; i < tests; i++) { candies[i] = Integer.parseInt(stdin.nextLine()); } Arrays.sort(candies); int unfairness = candies[candies.length - 1]; for(int i = 0; i <= candies.length - k; i++) { int temp = candies[i + k - 1] - candies[i]; if(unfairness > temp) { unfairness = temp; } } System.out.println(unfairness); stdin.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
'use strict'; const processData = input => { let lines = input.split('\n').map(i => parseInt(i)); let k = lines[1]; let sortedLines = lines.slice(2).sort((l,j) => l - j); let unfairness = sortedLines[sortedLines.length - 1]; for(let i = 0; i <= sortedLines.length - k; i++) { let temp = sortedLines[i + k - 1] - sortedLines[i]; if(unfairness > temp) { unfairness = temp } } console.log(unfairness); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); var _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Scala
1 2 3 4 5 6 |
object MaxMin extends App { val size = readInt() val k = readInt() val input = (1 to size).map(_ => readInt()).toVector.sorted println((0 to (size - k)).map(i => input(i + (k-1)) - input(i)).min) } |