https://app.codility.com/programmers/lessons/7-stacks_and_queues/fish/
Fish coding task - Learn to Code - Codility
N voracious fish are moving along a river. Calculate how many fish are alive.
app.codility.com
import java.util.Stack;
class Solution {
public int solution(int[] A, int[] B) {
/*
upstream : ↑
downstream : ↓
A : 4 8 6 5 7 3 1 2
B : 0 1 1 1 0 0 1 1
-------------------
Top of River
| 4 ↑ | alive
| 8 ↓ | alive
| 6 ↓ | dead
| 5 ↓ | dead
| 7 ↑ | dead
| 3 ↑ | dead
| 1 ↓ | alive
| 2 ↓ | alive
Bottom of River
*/
Stack<Integer> downstreamFishStack = new Stack<>();
int cnt = 0;
for (int i = 0; i < B.length; i++) {
if (B[i] == 0) {
while (!downstreamFishStack.isEmpty() && downstreamFishStack.peek() < A[i]) {
downstreamFishStack.pop();
}
if (downstreamFishStack.isEmpty()) {
cnt++;
}
} else {
downstreamFishStack.add(A[i]);
}
}
return cnt + downstreamFishStack.size();
}
}
[Lesson 8] Leader - EquiLeader (1) | 2025.01.20 |
---|---|
[Lesson 8] Leader - Dominator (1) | 2025.01.17 |
[Lesson 7] Stacks and Queues - StoneWall (0) | 2025.01.17 |
[Lesson 7] Stacks and Queues - Nesting (1) | 2025.01.16 |
[Lesson 7] Stacks and Queues - Brackets (0) | 2025.01.16 |
댓글 영역