상세 컨텐츠

본문 제목

[Lesson 7] Stacks and Queues - Fish

Codility Lessons 풀이

by 발발개발 2025. 1. 17. 16:06

본문

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();
    }
}

관련글 더보기

댓글 영역