Lesson 7 - Stone Wall

GwanMtCat·2023년 6월 9일
0

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:

class Solution { public int solution(int[] 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.

Write an efficient algorithm for the following assumptions:

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].


Stack을 이용해야 하는 건 감이 오는데, 다음과 같은 조건을 모두 추론해내는데 실패했다.

  • 이전 블록의 높이 값과 비교하여 이전 블록의 값이 높을 경우 stack에서 제거
  • 다음 블록의 높이 값이 더 큰 경우, stack에 넣고 count 증가
  • 이전 블록의 높이와 다음 블록의 높이가 같을 경우에는 count 할 필요 없음

stack.pop()이 아닌 stack.peek() 으로 볼 수 있다는 것도 오랜만에 알게됐다.

베스트 답안

import java.util.Stack;

class Solution {
    public int solution(int[] H) {
        Stack<Integer> stack = new Stack();

        int count = 0;

        for (int i=0; i<H.length; i++) {
            while (!stack.isEmpty() && stack.peek() > H[i]) {
                stack.pop();
            }

            if (stack.isEmpty() || stack.peek() < H[i]) {
                stack.push(H[i]);
                count++;
            }
        }

        return count;
    }
}

0개의 댓글