I am doing exercises on codility. I have spent two days on this problem with no improvement in my score. I get 100% on my correctness score, but fail some performance tests because it returns the wrong answer (not because of time or space complexity). My wrong results are always less than the expected answer. Can anyone think of a case where I need to add a stone that I am missing?
This is the prompt:
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 a zero-indexed array
H
ofN
positive integers.
H[I]
is the height of the wall fromI
toI+1
meters to the right of its left end. In particular,H[0]
is the height of the wall's left end andH[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 that, given a zero-indexed array
H
ofN
positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it.class Solution { public int solution(int[] H); }
For example, given array
H
containingN = 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.
Assume that:
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]
.Complexity:
- Expected worst-case time complexity is \$O(N)\$;
- Expected worst-case space complexity is \$O(N)\$, beyond input storage (not counting the storage required for input arguments).
- Elements of input arrays can be modified.
This is my solution:
import java.util.*;
class Solution {
public int solution(int[] H) {
// write your code in Java SE 8
LinkedList<Integer> stack = new LinkedList<Integer>();
int count = 1;
int lowest = H[0];
stack.push(H[0]);
if(H.length == 1){
return 1;
}
else{
for(int i = 1; i<H.length; i++){
if(H[i] > H[i-1]){
stack.push(H[i]);
count++;
}
if(H[i] < lowest){
while(stack.size() > 0){
stack.pop();
}
stack.push(H[i]);
lowest = H[i];
count++;
}
if(H[i] < H[i-1] && H[i] > lowest){
while(stack.size() > 0 && stack.peek() > H[i]){
stack.pop();
}
if(stack.size() > 0 && stack.peek() < H[i]){
stack.push(H[i]);
count++;
}
}
}
}
return count;
}
}
for(int i = 1; i<H.length; i++)
, are you sure you didn't mean to sayfor(int i=0)
? – Espouse