Created
December 7, 2019 18:02
-
-
Save bachiri/03992b7cd0a10bcb1d9f66b9fa5397f3 to your computer and use it in GitHub Desktop.
Solution for StoneWall Codility
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package codility.stackandqueues; | |
import java.util.Stack; | |
//Codility Lesson 7 | |
//Stacks and Queues | |
//Problem :StoneWall | |
//Link : https://app.codility.com/programmers/lessons/7-stacks_and_queues/ | |
public class StoneWall { | |
public static void main(String[] args) { | |
System.out.println("Stone needed are : " + solution(new int[]{8, 8, 5, 7, 9, 8, 7, 4, 8})); | |
System.out.println("Stone needed are : " + solution(new int[]{1, 2, 1})); | |
System.out.println("Stone needed are : " + solution(new int[]{1, 2, 0, 1, 5,6})); | |
System.out.println("Stone needed are : " + solution(new int[]{})); | |
} | |
public static int solution(int[] H) { | |
Stack<Integer> stack = new Stack<Integer>(); | |
int counter = 0; | |
int i = 0; | |
while (i < H.length) { | |
//If the element is 0 reset, no history needed as next one will be a new Block. | |
if (H[i] == 0) { | |
stack.clear(); | |
i++; | |
continue; | |
} | |
//The stack is not empty a base can be found | |
if (!stack.isEmpty()) { | |
//Is equal no block is needed same height | |
if (stack.peek() == H[i]) { | |
i++; | |
//The current element is small a new block needed to reach the height | |
} else if (stack.peek() < H[i]) { | |
counter++; | |
stack.push(H[i]); | |
i++; | |
//The current element is taller need to pop and reenter the while | |
} else { | |
stack.pop(); | |
} | |
//Stack is empty add a block | |
} else { | |
counter++; | |
stack.push(H[i]); | |
i++; | |
} | |
} | |
return counter; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment