Skip to content

Instantly share code, notes, and snippets.

@gokhanakkurt
Created October 18, 2019 08:44
Show Gist options
  • Save gokhanakkurt/846c5fb018bb9c93d67d2ae34cbc2a37 to your computer and use it in GitHub Desktop.
Save gokhanakkurt/846c5fb018bb9c93d67d2ae34cbc2a37 to your computer and use it in GitHub Desktop.
N voracious fish are moving along a river. Calculate how many fish are alive.
func calculateAliveFish(_ A : inout [Int], _ B : inout [Int]) -> Int {
if A.isEmpty {
return 0 // base case
}
var stack: [Int] = [Int]()
var survivals: Int = 0
for (index,elem) in A.enumerated() {
if B[index] == 0 {
while !stack.isEmpty {
guard let last = stack.last else { break }
if last < elem {
let _ = stack.popLast()
}else {
break
}
}
if stack.isEmpty {
survivals += 1 // one fish survived in the fight
}
}else {
stack.append(elem)
}
}
return survivals + stack.count
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment