Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Type of array and its maximum element
Next article icon

Maximum element in a sorted and rotated array

Last Updated : 07 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a sorted array arr[] (may contain duplicates) of size n that is rotated at some unknown point, the task is to find the maximum element in it. 

Examples: 

Input: arr[] = {5, 6, 1, 2, 3, 4}
Output: 6
Explanation: 6 is the maximum element present in the array.

Input: arr[] = {3, 2, 2, 2}
Output: 3
Explanation: 3 is the maximum element present in the array.

[Naive Approach] Linear Search - O(n) Time and O(1) Space

A simple solution is to use linear search to traverse the complete array and find a maximum. 

C++
// C++ program to find maximum element in a  // sorted rotated array using linear search #include <iostream> #include <vector> using namespace std;  // Function to find the maximum value int findMax(vector<int>& arr) {        int res = arr[0];      // Traverse over arr[] to find maximum element     for (int i = 1; i < arr.size(); i++)          res = max(res, arr[i]);      return res; }  int main() {     vector<int> arr = {5, 6, 1, 2, 3, 4};      cout << findMax(arr) << endl;     return 0; } 
C
#include <stdio.h> #include <stdlib.h>  // Function to find the maximum value int findMax(int arr[], int size) {     int res = arr[0];      // Traverse over arr[] to find maximum element     for (int i = 1; i < size; i++)         res = (res > arr[i]) ? res : arr[i];      return res; }  int main() {     int arr[] = {5, 6, 1, 2, 3, 4};     int size = sizeof(arr) / sizeof(arr[0]);      printf("%d\n", findMax(arr, size));     return 0; } 
Java
import java.util.Arrays;  public class GfG {        // Function to find the maximum value     public static int findMax(int[] arr) {         int res = arr[0];          // Traverse over arr[] to find maximum element         for (int i = 1; i < arr.length; i++)             res = Math.max(res, arr[i]);          return res;     }      public static void main(String[] args) {         int[] arr = {5, 6, 1, 2, 3, 4};          System.out.println(findMax(arr));     } } 
Python
# Function to find the maximum value def findMax(arr):     res = arr[0]      # Traverse over arr[] to find maximum element     for i in range(1, len(arr)):         res = max(res, arr[i])      return res  if __name__ == '__main__':     arr = [5, 6, 1, 2, 3, 4]     print(findMax(arr)) 
JavaScript
// Function to find the maximum value function findMax(arr) {     let res = arr[0];      // Traverse over arr to find maximum element     for (let i = 1; i < arr.length; i++)          res = Math.max(res, arr[i]);      return res; }  const arr = [5, 6, 1, 2, 3, 4];  console.log(findMax(arr)); 

Output
6 

[Expected Approach] Binary Search - O(log n) Time and O(1) Space

In Binary Search, we find the mid element and then decide whether to stop or to go to left half or right half. How do we decide in this case. Let us take few examples.

{4, 5, 6, 9, 10, 1, 2}, mid = (0 + 7) / 2 = 3. arr[3] is 9. How to find out that we need to go to the right half (Note that the largest element is in right half)? We can say if arr[mid] > arr[lo], then we go the right half. So we change low = mid. Please note that arr[mid] can also be the largest element.

{50, 10, 20, 30, 40}, mid = (0 + 4)/2 = 2. arr[2] is 20. If arr[mid] is smaller than or equal to arr[lo], then we go to the left half.

How do we terminate the search? One way could be to check if the mid is smaller than both of its adjacent, then we return mid. This would require a lot of condition checks like if adjacent indexes are valid or not and then comparing mid with both. We use an interesting fact here. If arr[lo] <= arr[hi], then the current subarray must be sorted, So we return arr[hi]. This optimizes the code drastically as we do not have to explicitly check the whole sorted array.

C++
#include <bits/stdc++.h> using namespace std;  int findMax(vector<int> &arr) {     int lo = 0, hi = arr.size() - 1;      while (lo < hi)     {         // If the current subarray is already sorted,         // the maximum is at the hi index         if (arr[lo] <= arr[hi])             return arr[hi];                  int mid = (lo + hi) / 2;          // The left half is sorted, the maximum must          // be either arr[mid] or in the right half.         if (arr[mid] > arr[lo])             lo = mid;         else             hi = mid - 1;     }      return arr[lo];  }  int main() {     vector<int> arr = {7, 8, 9, 10, 1, 2, 3, 4, 5};     cout << findMax(arr);     return 0; } 
C
#include <stdio.h>  int findMax(int arr[], int n) {     int lo = 0, hi = n - 1;      while (lo < hi) {                // If the current subarray is already sorted,         // the maximum is at the hi index         if (arr[lo] <= arr[hi])             return arr[hi];                  int mid = (lo + hi) / 2;          // The left half is sorted, the maximum must          // be either arr[mid] or in the right half.         if (arr[mid] > arr[lo])             lo = mid;         else             hi = mid - 1;     }      return arr[lo];  }  int main() {     int arr[] = {7, 8, 9, 10, 1, 2, 3, 4, 5};     int n = sizeof(arr) / sizeof(arr[0]);     printf("%d", findMax(arr, n));     return 0; } 
Java
import java.util.Arrays;  public class Main {     public static int findMax(int[] arr) {         int lo = 0, hi = arr.length - 1;          while (lo < hi) {                        // If the current subarray is already sorted,             // the maximum is at the hi index             if (arr[lo] <= arr[hi])                 return arr[hi];                          int mid = (lo + hi) / 2;              // The left half is sorted, the maximum must              // be either arr[mid] or in the right half.             if (arr[mid] > arr[lo])                 lo = mid;             else                 hi = mid - 1;         }          return arr[lo];      }      public static void main(String[] args) {         int[] arr = {7, 8, 9, 10, 1, 2, 3, 4, 5};         System.out.println(findMax(arr));     } } 
Python
def find_max(arr):     lo, hi = 0, len(arr) - 1      while lo < hi:                # If the current subarray is already sorted,         # the maximum is at the hi index         if arr[lo] <= arr[hi]:             return arr[hi]                  mid = (lo + hi) // 2          # The left half is sorted, the maximum must          # be either arr[mid] or in the right half.         if arr[mid] > arr[lo]:             lo = mid         else:             hi = mid - 1      return arr[lo]  arr = [7, 8, 9, 10, 1, 2, 3, 4, 5] print(find_max(arr)) 
C#
using System;  class Program {     static int FindMax(int[] arr) {         int lo = 0, hi = arr.Length - 1;          while (lo < hi) {                        // If the current subarray is already sorted,             // the maximum is at the hi index             if (arr[lo] <= arr[hi])                 return arr[hi];                          int mid = (lo + hi) / 2;              // The left half is sorted, the maximum must              // be either arr[mid] or in the right half.             if (arr[mid] > arr[lo])                 lo = mid;             else                 hi = mid - 1;         }          return arr[lo];      }      static void Main() {         int[] arr = {7, 8, 9, 10, 1, 2, 3, 4, 5};         Console.WriteLine(FindMax(arr));     } } 
JavaScript
function findMax(arr) {     let lo = 0, hi = arr.length - 1;      while (lo < hi) {              // If the current subarray is already sorted,         // the maximum is at the hi index         if (arr[lo] <= arr[hi])             return arr[hi];                  let mid = Math.floor((lo + hi) / 2);          // The left half is sorted, the maximum must          // be either arr[mid] or in the right half.         if (arr[mid] > arr[lo])             lo = mid;         else             hi = mid - 1;     }      return arr[lo];  }  const arr = [7, 8, 9, 10, 1, 2, 3, 4, 5]; console.log(findMax(arr)); 

Output
10



Next Article
Type of array and its maximum element
author
md1844
Improve
Article Tags :
  • Divide and Conquer
  • Searching
  • C++
  • DSA
  • Arrays
  • Binary Search
Practice Tags :
  • CPP
  • Arrays
  • Binary Search
  • Divide and Conquer
  • Searching

Similar Reads

  • Minimum in a Sorted and Rotated Array
    Given a sorted array of distinct elements arr[] of size n that is rotated at some unknown point, the task is to find the minimum element in it. Examples: Input: arr[] = [5, 6, 1, 2, 3, 4]Output: 1Explanation: 1 is the minimum element present in the array. Input: arr[] = [3, 1, 2]Output: 1Explanation
    9 min read
  • Type of array and its maximum element
    Given an array, it can be of 4 types. Ascending Descending Ascending Rotated 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} Outp
    15+ min read
  • Check if an array is sorted and rotated
    Given an array arr[] of size n, the task is to return true if it was originally sorted in non-decreasing order and then rotated (including zero rotations). Otherwise, return false. The array may contain duplicates. Examples: Input: arr[] = { 3, 4, 5, 1, 2 }Output: YESExplanation: The above array is
    7 min read
  • Javascript Program for Search an element in a sorted and rotated array
    An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time.  Exam
    7 min read
  • Largest element in an Array
    Given an array arr. The task is to find the largest element in the given array. Examples: Input: arr[] = [10, 20, 4]Output: 20Explanation: Among 10, 20 and 4, 20 is the largest. Input: arr[] = [20, 10, 20, 4, 100]Output: 100 Table of Content Iterative Approach - O(n) Time and O(1) SpaceRecursive App
    7 min read
  • Maximum XOR Queries With an Element From Array
    Given an array arr[] of size n containing non-negative integers and also given a list of q queries in a 2D array queries[][], where each query is of the form [xi, mi]. For each query, you need to find the maximum value of (xi XOR arr[j]) such that arr[j] is less than or equal to mi. In simple terms,
    15+ min read
  • Second Largest Element in an Array
    Given an array of positive integers arr[] of size n, the task is to find second largest distinct element in the array. Note: If the second largest element does not exist, return -1. Examples: Input: arr[] = [12, 35, 1, 10, 34, 1]Output: 34Explanation: The largest element of the array is 35 and the s
    14 min read
  • Find the maximum element in the array other than Ai
    Given an array arr[] of size N. The task is to find maximum element among N - 1 elements other than arr[i] for each i from 1 to N.Examples: Input: arr[] = {2, 5, 6, 1, 3} Output: 6 6 5 6 6 Input: arr[] = {1, 2, 3} Output: 3 3 2 Approach: An efficient approach is to make prefix and suffix array of ma
    6 min read
  • Rotation Count in a Rotated Sorted array
    Given an array arr[] having distinct numbers sorted in increasing order and the array has been right rotated (i.e, the last element will be cyclically shifted to the starting position of the array) k number of times, the task is to find the value of k. Examples: Input: arr[] = {15, 18, 2, 3, 6, 12}O
    13 min read
  • Find k largest elements in an array
    Given an array arr[] and an integer k, the task is to find k largest elements in the given array. Elements in the output array should be in decreasing order. Examples: Input: [1, 23, 12, 9, 30, 2, 50], k = 3Output: [50, 30, 23] Input: [11, 5, 12, 9, 44, 17, 2], k = 2Output: [44, 17] Table of Content
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences