Created
December 26, 2022 05:30
-
-
Save dharshan/430e5226bdc7a8064d64d2b647ee7e8c to your computer and use it in GitHub Desktop.
Voracious fish problem ruby using stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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