LeetCode: Largest Number At Least Twice of Others
Question
In a given integer array nums, there is always exactly one largest element.
Find whether the largest element in the array is at least twice as much as every other number in the array.
If it is, return the index of the largest element, otherwise return -1.
Solution
def dominant_index(nums)
max_num = nums.max
arr_dup = nums.dup
nums.delete(max_num)
nums.select do |num|
return -1 if max_num < num*2
end
arr_dup.index(max_num)
end
Comments