Maximum element in a sorted and rotated array
Last Updated :
07 Nov, 2024
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));
[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));
Similar Reads
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
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: 100Table of ContentIterative Approach - O(n) Time and O(1) SpaceRecursive Appro
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}Ou
12 min read
Find the maximum subarray XOR in a given array Given an array of integers. The task is to find the maximum subarray XOR value in the given array. Examples: Input: arr[] = {1, 2, 3, 4}Output: 7Explanation: The subarray {3, 4} has maximum XOR value Input: arr[] = {8, 1, 2, 12, 7, 6}Output: 15Explanation: The subarray {1, 2, 12} has maximum XOR val
15+ min read
Collect maximum points in an array with k moves Given an array of integer and two values k and i where k is the number of moves and i is the index in the array. The task is to collect maximum points in the array by moving either in single or both directions from given index i and making k moves. Note that every array element visited is considered
9 min read
Find k maximum elements of array in original order Given an array arr[] and an integer k, we need to print k maximum elements of given array. The elements should printed in the order of the input.Note : k is always less than or equal to n. Examples: Input : arr[] = {10 50 30 60 15} k = 2 Output : 50 60 The top 2 elements are printed as per their app
11 min read
Maximum sum of increasing order elements from n arrays Given n arrays of size m each. Find the maximum sum obtained by selecting a number from each array such that the elements selected from the i-th array are more than the element selected from (i-1)-th array. If maximum sum cannot be obtained then return 0.Examples: Input : arr[][] = {{1, 7, 3, 4}, {4
13 min read
Find the maximum elements in the first and the second halves of the Array , Given an array arr[] of N integers. The task is to find the largest elements in the first half and the second half of the array. Note that if the size of the array is odd then the middle element will be included in both halves.Examples: Input: arr[] = {1, 12, 14, 5} Output: 12, 14 First half is {1
6 min read
Sort a Rotated Sorted Array You are given a rotated sorted array and your aim is to restore its original sort in place.Expected to use O(1) extra space and O(n) time complexity. Examples: Input : [3, 4, 1, 2] Output : [1, 2, 3, 4] Input : [2, 3, 4, 1] Output : [1, 2, 3, 4] We find the point of rotation. Then we rotate array us
11 min read
Maximum sum of i*arr[i] among all rotations of a given array Given an integer array arr[] of size n. The task is to find the maximum value of the sum of the value of i * arr[i] where i varies from 0 to n-1. The only operation allowed is to rotate the array any number of times.Examples: Input: arr[] = [8, 3, 1, 2]Output: 29Explanation: Out of all the possible
13 min read