Skip to content

Instantly share code, notes, and snippets.

@dharshan
Created December 26, 2022 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dharshan/430e5226bdc7a8064d64d2b647ee7e8c to your computer and use it in GitHub Desktop.
Save dharshan/430e5226bdc7a8064d64d2b647ee7e8c to your computer and use it in GitHub Desktop.
Voracious fish problem ruby using stack
class Fish
def solution(weights, direction)
stack = []
survivor_count = 0
weights.each_with_index do |elem, idx|
if direction[idx] == 1
stack.push(elem)
else
if stack.empty?
survivor_count += 1
next
end
last = stack.pop
if last > elem
stack.push(last)
end
end
end
survivor_count + stack.length
end
end
puts Fish.new.solution([10, 8, 2, 6, 7], [1, 0, 0, 0, 0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment