Created
October 18, 2019 08:44
-
-
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.
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
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