Tuesday 7 February 2017

Little Monk and Balanced Parantheses

Little Monk and Balanced Parentheses

Given an array of positive and negative integers, denoting different types of parentheses. The positive numbers

xi denotes opening parentheses of type xi and negative number −xi denotes closing parentheses of type xi.

Open parentheses must be closed by the same type of parentheses. Open parentheses must be closed in the

correct order, i.e., never close an open pair before its inner pair is closed (if it has an inner pair). Thus,

[1,2,−2,−1]

is balanced, while [1,2,−1,−2]

is not balanced.

You have to find out the length of the longest sub array that is balanced.

Input Format:

First line contains an input N

(1≤N≤2∗105), denoting the number of parentheses. Second line contains N space separated integers. xi

(−105≤xi≤105,xi≠0) denoting the ith

parentheses of the array.

Output Format:

Print the length of the longest subarray that is balanced.

SAMPLE INPUT

5

1 -1 2 3 -2

SAMPLE OUTPUT

2

Explanation

The longest subarray that is balanced is (1,−1). (2,3,−2) is not balanced as (3) is not balanced.

#include <stdio.h>
int stack[50],top=-1;
void push(int t)
{            
       top=top+1;
stack[top]=t;
}
int pop()
{
   int te=stack[top];
   top=top-1;
   return te;
}
main()
{
   int a[50],n=4,i,temp;
   for(i=0;i<n;i++)
scanf("%d",&a[i]);
   for(i=0;i<n;i++)
   {
if(a[i] > 0)
push(a[i]);
else
{
               if(top == -1)
{
printf("invalid expression");
exit(0);
}
              temp = pop();
              else
{
if(temp !=(-a[i]))
{
printf("invalid expression");
exit(0);
}
}
}
   }
   if(top >=0 )
printf("invalid");
   else
printf("valid");
}

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete