def solution(arr):
stack = []
count = 0
for h in arr:
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
#Challenge
Source | Language | Runtime |
---|---|---|
codility | python |
You are going to build a stone wall. The wall should be straight and
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 that, given an array
For example, given array
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. See here for a pictural representation of this arrangement.
#Solution
The thing to note here is that we only need a new block when the height of the
current block doesn't match the previous one. Consider
Another thing to note is that we can repurpose earlier blocks for new ones. Consider
- one 3 length block of height 1.
- one 1 length block of height 1.
---
|X|
---
---------
| X |
---------
The pattern we can observe here is that as we encounter newer, taller, blocks we
push back our current smaller blocks and consider only blocks of increasing height
(eg.
NOTE: The actual arrangement of blocks is beyond the scope of this challenge,
we are concerned only with the minimum number of blocks needed to satisfy
For those familiar with data structures, this pattern of last in first out will probably remind you of a stack. In this solution we've implemented a rudimentary stack which we either exhaust or fill up using the above two conditions until the array of heights is all used.