267. Fish

아현·2021년 8월 15일
0

Algorithm

목록 보기
279/400
post-custom-banner



1. JavaScript


function solution(A, B) {
    let downFish = [];
    let survived= 0;

    for(let i = 0; i < A.length; i++) {
        if(B[i] === 1) {
            downFish.push(i);
        } else {
            while(downFish.length !== 0) {
                const downFishIdx = downFish.pop();
                if(A[downFishIdx] > A[i]) { //올라가는 물고기가 진 경우
                    downFish.push(downFishIdx);
                    break;
                }
            }

            if(downFish.length === 0) survived++; //내려오는 물고기가 없는 경우
        }
    }

    survived += downFish.length;

    return survived;
}



2. Python



def solution(A, B):
    
    stack = []
    cnt = 0

    for i in range(len(A)):
        if B[i] == 1:
            stack.append(A[i])
        else:
            while stack:
                f = stack[-1]
                if f > A[i]:
                    break
                else:
                    stack.pop()
            if not stack:
                cnt += 1
    
    return cnt + len(stack)
profile
For the sake of someone who studies computer science
post-custom-banner

0개의 댓글