- Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path1675-minimize-deviation-in-array.rb
43 lines (35 loc) · 947 Bytes
/
1675-minimize-deviation-in-array.rb
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# frozen_string_literal: true
# 1675. Minimize Deviation in Array
# https://leetcode.com/problems/minimize-deviation-in-array
# @param {Integer[]} nums
# @return {Integer}
defminimum_deviation(nums)
nums.uniq!
nums.map!{ |x| x.odd? ? x * 2 : x}.sort!
diff=nums.last - nums.first
stack=[]
loopdo
ifstack.empty? || nums.last.to_i > stack.first
max=nums.pop
else
max=stack.shift
end
breakifmax.odd?
stack.pushmax / 2
max=[stack.first,nums.last].compact.max
min=[stack.last,nums.first].compact.min
diff=[diff,max - min].min
end
diff
end
# ********************#
# TEST #
# ********************#
require"test/unit"
classTest_minimum_deviation < Test::Unit::TestCase
deftest_
assert_equal1,minimum_deviation([1,2,3,4])
assert_equal3,minimum_deviation([4,1,5,20,3])
assert_equal3,minimum_deviation([2,10,8])
end
end