I was wondering if there is a programmatic way to determine if an array has the pattern of a perfect mountain, without valleys. (Example in the image)
Source: https://leetcode.com/problems/valid-mountain-array/
Edit:
My attempt in C:
#include<stdio.h>
int AscOrDes(int a[], int first, int last)
{
int i;
for(i=first; i<last; i++)
{
if(a[i]>a[i+1])
return(1);
else if(a[i]<a[i+1])
return(2);
}
return 0;
}
int main() {
int a[1000],n,i,big=0,r1,r2;
scanf("%d",&n);
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
for(i=0; i<n; i++)
{
if(a[i]>=a[big])
big=i;
}
r1=AscOrDes(a, 0, big);
r2=AscOrDes(a, big, n);
if(r1==2 && r2==1 && big!=0 && big!=n-1)
printf("True");
else
printf("False");
return 0;
}
The above code doesn't work for the following inputs:
8
1 3 2 5 4 3 2 0
It gives the output:
True
Even though it isn't a perfect mountain array.
What I have done in my program is check which element is the largest (big
), and checked if the elements on the left side of the largest element are in ascending order and those on the right side are in descending order (how the mountain should be).