```
def next_greater_elements(nums)
n = nums.size
res = []
stack = []
(n-1).downto(0) do |i|
stack << i
end
(n-1).downto(0) do |i|
res[i] = -1
stack.pop while !stack.empty? && nums[stack[-1]] <= nums[i]
res[i] = nums[stack[-1]] if !stack.empty?
stack << i
end
res
end
```