StoneWall

HeeSeong·2021년 6월 12일
0

Codility

목록 보기
21/34
post-thumbnail

🔗 문제 링크

https://app.codility.com/programmers/lessons/7-stacks_and_queues/stone_wall/start/


❔ 문제 설명


You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. The height of the wall is specified by an array H of N positive integers. H[I] is the height of the wall from I to I+1 meters to the right of its left end. In particular, H[0] is the height of the wall's left end and H[N−1] is the height of the wall's right end.

The wall should be built of cuboid stone blocks (that is, all sides of such blocks are rectangular). Your task is to compute the minimum number of blocks needed to build the wall.

Write a function:

def solution(H)

that, given an array H of N positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it.

For example, given array H containing N = 9 integers:

H[0] = 8 H[1] = 8 H[2] = 5
H[3] = 7 H[4] = 9 H[5] = 8
H[6] = 7 H[7] = 4 H[8] = 8

the function should return 7. The figure shows one possible arrangement of seven blocks.



⚠️ 제한사항


  • N is an integer within the range [1..100,000];

  • each element of array H is an integer within the range [1..1,000,000,000].



💡 풀이 (언어 : Python)


어려워서 풀이를 참고했다. 풀이의 아이디어는 스택에 없을 때 처음 나온 값과 스택의 최근 값보다 큰 값이 나왔을 때 카운트해주고 스택에 쌓아준다. 그리고 스택의 값보다 작은 값이 나오면 스택에서 그 값보다 큰 것들은 계속 스택에서 제거해준다. 스택의 값과 나온 값이 같으면 무시하고 스킵한다. 시간복잡도는 O(N)O(N)

def solution(H):
    stack = list()
    count = 0
    for h in H:
        while len(stack) != 0 and stack[-1] > h:
            stack.pop()
        if len(stack) == 0 or stack[-1] < h:
            count += 1
            stack.append(h)

    return count
profile
끊임없이 성장하고 싶은 개발자

0개의 댓글