룬아님의 취중코딩

Codility 21번 StoneWall 본문

개발/알고리즘

Codility 21번 StoneWall

룬아님 2019. 9. 9. 16:31

StoneWall

 

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

    Copyright 2009–2019 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

 

import java.util.*;

class Solution {
    public int solution(int[] H) {
        Stack<Integer> block = new Stack<>();
        int cnt = 0;
        for (int i = 0; i < H.length; i++) {
            if (block.size() == 0) {
                block.push(H[i]);
            } else if (block.peek() < H[i]) {
                block.push(H[i]);
            } else if (block.peek() > H[i]) {
                while (block.size() != 0 && block.peek() > H[i]) {
                    block.pop();
                    cnt++;
                }
                if (block.size() == 0 || block.peek() != H[i]) {
                    block.push(H[i]);
                }
            }
        }

        return cnt + block.size();
    }
}

https://app.codility.com/demo/results/trainingP3DW6H-TFQ/

반응형

'개발 > 알고리즘' 카테고리의 다른 글

Codility 22번 Dominator  (0) 2019.09.15
Codility 20번 Nesting  (0) 2019.09.09
Codility 19번 Fish  (0) 2019.09.09
Codility 18번 Brackets  (0) 2019.09.02
Codility 17번 NumberOfDiscIntersections  (0) 2019.09.01
Comments