Program to find the maximum number in rotated list in C++

C++Server Side ProgrammingProgramming

Suppose there is an array, and that is sorted, consider that array is rotated at some pivot, that is unknown to us. So we have to find the maximum from that rotated array. So if the array is like[3,4,5,1,2], then the output will be 5.

To solve this, we will follow these steps −

  • low := 0 and high := last index of array, n := size of array, ans := 0

  • while low <= high

    • mid := low + (high - low)/2

    • if arr[low] < arr[mid], then ans := maximum of ans and arr[low], low := mid + 1

    • else if arr[high] > arr[mid], then ans := maximum of ans and arr[mid], high := mid – 1

    • else if low = mid, then ans := maximum of ans and arr[low], low := mid + 1

    • else if high = mid, then ans := maximum of ans and arr[high], high := mid - 1

  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int search(vector <int>& arr, int low, int high){
      if(low == high){
         return arr[low];
      }
      int mid = low + (high - low) / 2;
      int ans = 0;
      if(arr[low] < arr[mid]){
         ans = max(arr[low], search(arr, mid, high));
      }
      else if (arr[high] > arr[mid]){
         ans = max(arr[mid], search(arr, low, mid));
      }
      else if(arr[low] == arr[mid]){
         ans = max(arr[low], search(arr, low + 1, high));
      }
      else if(arr[high] == arr[mid]){
         ans = max(arr[high], search(arr, low, high - 1));
      }
      return ans;
   }
   int findMax(vector<int>& nums) {
      return search(nums, 0, nums.size() - 1);
   }
};
main(){
   Solution ob;
   vector<int> v = {4,5,5,5,6,8,2,3,4};
   cout <<(ob.findMax(v));
}

Input

[4,5,5,5,6,8,2,3,4]

Output

8
raja
Published on 08-Oct-2020 10:22:37
Advertisements