StoneWall solution
Task
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:
int solution(vector<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].
Solution 1
int solution(vector<int> &H) {
int numEqual = 0;
for (size_t i = 0; i < H.size(); i++) {
int height = H[i];
for (size_t j = i + 1; j < H.size(); j++) {
int next = H[j];
if (next == height) {
numEqual++;
break;
}
if (next < height) {
break;
}
}
}
return H.size() – numEqual;
}
Results
Correctness | 100% |
Performance | 77% |
Time Complexity | O(N) (average) |
Solution 2
#include <stack>
int solution(vector<int> &H) {
// list of previous column sizes smaller than current
stack<int> prevSmaller;
int numEqual = 0;
for (size_t i = 0; i < H.size(); i++) {
int height = H[i];
while (prevSmaller.size() > 0) {
int prev = prevSmaller.top();
if (prev == height) {
numEqual++;
prevSmaller.pop();
break;
} else {
if (prev > height) {
prevSmaller.pop();
} else {
break;
}
}
}
prevSmaller.push(height);
}
return H.size() – numEqual;
}
Results
Correctness | 100% |
Performance | 100% |
Time Complexity | O(N) |
Test Function
This code tests the solution
int main() {
vector<int> A9{8, 8, 5, 7, 9, 8, 7, 4, 8};
assert(solution(A9) == 7);
vector<int> A2{1000000000, 7, 6, 5, 4, 3, 2, 1};
assert(solution(A2) == 8);
vector<int> A3(100000, 1);
assert(solution(A3) == 1);
vector<int> A4(100000, 1000000000);
assert(solution(A4) == 1);
}