본문 바로가기

코딩테스트/codility

Fish

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

 

지난번에 풀었던 PassingCars(https://nyaaong.tistory.com/67) 문제와 유사하다. 다만 서로 만나는 물고기들의 크기를 비교하는 로직이 추가되었다.

 

import java.util.*;

class Solution {

    final int upstream = 0;
    final int downstream = 1;

    public int solution(int[] A, int[] B) {

        Stack<Integer> fishes = new Stack();

        int alive = 0;
        for (int i = 0; i < A.length; i++) {
            int size = A[i];
            int direction = B[i];

            if (direction == upstream) {
                if (isAlive(size, fishes)) alive++;
            } else {
                fishes.push(size);
            }
            
        }

        return alive + fishes.size();

    }

    boolean isAlive(int size, Stack<Integer> fishes) {

        while (!fishes.isEmpty()) {

            int fish = fishes.peek();

            if (fish < size) {
                fishes.pop();
            } else {
                return false;
            }

        }

        return true;


    }
}

'코딩테스트 > codility' 카테고리의 다른 글

StoneWall  (0) 2023.10.06
Triangle  (0) 2023.10.04
MaxProductOfThree  (0) 2023.09.29
PassingCars  (0) 2023.09.29
Distinct  (0) 2023.09.29