I used the same logic, and wrote the code in C. Tried a lot of Cases. Can anyone figure out something?
#include <stdio.h>
#include <stdlib.h>
void push(int m, int * a, int * top) {
// printf("%d Pushed!!\n", m);
(*top)++;
a[*top] = m;
}
void pop(int *a, int *top) {
// printf("%d Popped!!\n", a[*top]);
a[*top] = -1;
(*top)--;
}
int main(void) {
int n;
scanf("%d",&n);
while(n) {
int m, counter = 1, rem, flag = 0, flag2 = 0, flag3 = 0;
int i;
int a[1000], *top;
top = (int*)malloc(1*sizeof(int));
*top = 0;
a[0] = -1;
for (i = 0; i < n; i++) {
scanf("%d",&m);
if (m == 1) flag3 = 1;
if (flag2 == 0) {
while (a[*top] == (counter + 1)/* && m == counter*/ && flag3 == 1) {
pop(a,top);
counter++;
// printf("Value of m : %d\n",m);
// m++;
flag = 1;
}
if (flag == 1) {
flag = 0;
continue;
}
if (m == counter){
counter++;
continue;
}
else {
if (a[*top] > m || a[*top] < 0) {
push(m,a,top);
continue;
}
else {
// printf("Value of m: %d\nValue of top: %d\nStack top: %d\n",m,*top,a[*top]);
// printf("Value of Counter: %d\n", counter);
flag2 = 1;
continue;
// break;
}
}
}
}
if (flag2 == 1){
printf("no\n");
}
else {
printf("yes\n");
}
scanf("%d",&n);
free(top);
}
return 0;
}