#include <bits/stdc++.h>
using namespace std;
struct node {
int key;
struct node *left, *right;
};
struct node* newNode(int item)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
struct node* insert(struct node* node, int key)
{
if (node == NULL)
return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
return node;
}
int maxDepth(node* node)
{
if (node == NULL)
return 0;
else {
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
if (lDepth > rDepth)
return (lDepth + 1);
else
return (rDepth + 1);
}
}
int maxHeight(int a[], int n)
{
struct node* rootA = NULL;
rootA = insert(rootA, a[0]);
for (int i = 1; i < n; i++)
insert(rootA, a[i]);
struct node* rootB = NULL;
rootB = insert(rootB, a[n - 1]);
for (int i = n - 2; i >= 0; i--)
insert(rootB, a[i]);
int A = maxDepth(rootA) - 1;
int B = maxDepth(rootB) - 1;
return max(A, B);
}
int main()
{
int a[] = { 2, 1, 3, 4 };
int n = sizeof(a) / sizeof(a[0]);
cout << maxHeight(a, n);
return 0;
}