Java

mail@pastecode.io avatar
unknown
java
a year ago
688 B
2
Indexable
Never
public static int getFinalSize(int[] arr, int n) {
    Stack<Integer> stack1 = new Stack<>();
    Stack<Integer> stack2 = new Stack<>();

    for (int i = 0; i < n; i++) {
        if (stack1.isEmpty()) {
            stack1.push(arr[i]);
        } else if (stack2.isEmpty()) {
            stack2.push(arr[i]);
        } else {
            if (stack1.peek() == arr[i] && stack2.peek() == arr[i]) {
                continue;
            } else if (stack1.peek() == arr[i] && stack2.peek() != arr[i]){
                stack2.push(arr[i]);
            } else {
                stack1.push(arr[i]);
            }
        }
    }

    return stack1.size() + stack2.size();
}