Skip to content

Instantly share code, notes, and snippets.

@allenhwkim
Last active July 5, 2022 21:33
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 allenhwkim/0a3bdc8ea788dec6f8032c199de4033f to your computer and use it in GitHub Desktop.
Save allenhwkim/0a3bdc8ea788dec6f8032c199de4033f to your computer and use it in GitHub Desktop.
/**
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