Last active
July 5, 2022 21:33
-
-
Save allenhwkim/0a3bdc8ea788dec6f8032c199de4033f to your computer and use it in GitHub Desktop.
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
/** | |
given two non-empty arrays A and B consisting of N integers, returns the number of fish that will stay alive. | |
For example, given the arrays shown above, the function should return 2, as explained above. | |
Write an efficient algorithm for the following assumptions: | |
N is an integer within the range [1..100,000]; | |
each element of array A is an integer within the range [0..1,000,000,000]; | |
each element of array B is an integer that can have one of the following values: 0, 1; | |
the elements of A are all distinct. | |
*/ | |
function solution(A, B) { | |
var downStream = [] | |
var upStream = [] | |
var direction, UP = 0, DOWN = 1; | |
for (var i = 0; i < A.length; i++) { | |
direction = B[i] | |
if (direction === DOWN) { | |
// if fish goes down, line up those | |
downStream.push(A[i]); | |
} else if (direction === UP) { | |
// if fish goes up, meet all downstream fishes | |
// if eats a downstream fish, meet next downstream fish | |
// if eats all downstream fishes, survived!! | |
// if eaten by bigger downstream fish, process next | |
const upFish = A[i]; | |
while (downStream.length > 0) { | |
var downFish = downStream.slice(-1); // get the latest downFish | |
if (downFish > upFish) { // downFish wins, process next | |
break | |
} else { // downFish eaten by upFish. Let's meet next downFish | |
downStream.pop(); | |
} | |
} | |
// upFish eats all downFishes, survived!! | |
if (downStream.length === 0) { | |
upStream.push(upFish) | |
} | |
} | |
} | |
return downStream.length + upStream.length | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment