Topic: Arrays
1) Peak Element | Easy |
Question
Input: n = 3, arr[] = {1, 2, 3}
Output: 1
Explanation: If the index returned is 2, then the output
printed will be 1. Since arr[2] = 3 is greater than
its adjacent elements, and there is no element after
it, we can consider it as a peak element.
No other index satisfies the same property,
so answer will be printed as 0.
Program
public int peakElement(int[] arr,int n)
{
for(int i=0;i<n-1;i++){
if((arr[i]>arr[i+1])||(arr[i]==arr[i+1])){
return i;
}
else{
continue;
}
}
return n-1;
}
Time Complexity : O(n)
Space Complexity : O(1)
๐ Thankyou for being part of 200 days of DSA.
ย