Open In App

Type of array and its maximum element

Last Updated : 08 Jul, 2022
Comments
Improve
Suggest changes
8 Likes
Like
Report

Given an array, it can be of 4 types. 

  1. Ascending 
  2. Descending 
  3. Ascending Rotated 
  4.  Descending Rotated 

Find out which kind of array it is and return the maximum of that array.

Examples: 

Input :  arr[] = { 2, 1, 5, 4, 3}
Output : Descending rotated with maximum element 5

Input :  arr[] = { 3, 4, 5, 1, 2}
Output : Ascending rotated with maximum element 5

Asked in : Amazon Interview

Implementation:  

1- First, check if the whole array is in 
   increasing order, if yes then print arr[n-1].
   and return.

2- If above statement doesn't run even single
   time that means an array is in decreasing 
   order from starting. Two cases arise:
   
      a) Check if the whole array is in 
         decreasing order, if yes then 
         print arr[0] and return.
     (b) Otherwise, the array is descending
         rotated and the maximum element will
         be the index before which array was 
         decreasing.

3- If first point partially satisfies that 
   means the whole array is not in increasing 
   order that means an array is ascending 
   rotated and the maximum element will be the
   point from where it starts decreasing.

Implementation:

C++
Java Python3 C# PHP JavaScript

Output
Ascending rotated with maximum element =  6
Descending rotated with maximum element = 7
Ascending with maximum element = 8
Descending with maximum element =  9

Time Complexity : O(n) 
Auxiliary Space : O(1)

Another approach: Iterate through the array once and store the indices of the first and the last occurrences of the minimum and the maximum element of the array. Now there are four cases: 

  1. If the first occurrence of the minimum element is at the beginning of the array and the last occurrence of the maximum element is at the end of the array, then the array is in ascending order. For example, {1, 1, 1, 2, 3, 4, 5, 6, 6, 6}.
  2. If the first occurrence of the maximum element is at the beginning of the array and the last occurrence of the minimum element is at the end of the array, then the array is in descending order. For example, {6, 6, 6, 5, 4, 3, 2, 1, 1, 1}.
  3. If the first occurrence of the maximum element is equal to the last occurrence of the minimum element + 1 then the array is in descending rotated order. For example, {3, 2, 1, 1, 1, 6, 6, 6, 5, 4}.
  4. If the first occurrence of the minimum element is equal to the last occurrence of the maximum element + 1 then the array is in ascending rotating order. For example, {4, 5, 6, 6, 6, 1, 1, 1, 2, 3}.

Below is the implementation of the above approach:  

C++
Java Python3 C# JavaScript

Output
Ascending rotated with maximum element = 6

Next Article
Article Tags :
Practice Tags :

Similar Reads