문제
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:
function 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.
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].
코드
function solution(H) {
const n = H.length;
const stack = [];
let result = 0;
for (let i = 0; i < n; i++) {
while(stack.length > 0 && H[i] < stack[stack.length - 1]) {
stack.pop();
}
if (stack.length === 0 || H[i] > stack[stack.length - 1]) {
result += 1;
stack.push(H[i]);
}
}
return result;
}
풀이
맨 처음엔 아래 사진과 같이 이전블럭의 높이와 다음블럭의 높이 비교를 통해 자르는 방식으로 생각하고 접근했었는데 하다보면서 코드가 점점 더러워지는게 느껴져서 다시 리셋!
(이전 블럭의 높이 > 현재 블럭의 높이) 이고 스택에 값이 있을 경우 조건을 만족할 때 까지 스택에서 pop!
(이전 블럭의 높이 < 현재 블럭의 높이) 이거나 스택이 비었을 경우 : 추가로 블럭이 필요하므로 스택에 넣고 result 증가!
'Algorithm' 카테고리의 다른 글
(Codility) MinPerimeterRectangle - Javascript (0) | 2021.07.17 |
---|---|
(Coldility) EquiLeader - Javascript (0) | 2021.07.16 |
(leetcode) Rotate Array (0) | 2021.05.09 |
(leetcode) Longest Substring Without Repeating Characters (0) | 2021.05.02 |
(프로그래머스) N-Queen (0) | 2021.02.26 |
댓글