Hacker Rank Solutions: Angry Children

Hacker Rank Solutions: Angry Children

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  n = gets.to_i
  k = gets.to_i
  candy = []
  n.times do |i|
    candy[i] = gets.to_i
  end

  candy.sort!

  # sliding widow
  j = k
  i = 0
  lowest_dif = Float::INFINITY

  while j <= candy.length do
    dif = candy[j - 1] - candy[i]
    lowest_dif = dif if dif < lowest_dif

    break if lowest_dif == 0

    j += 1
    i += 1
  end

  puts lowest_dif

Comments