Maximum value in a bitonic array
PROBLEM :
Given an array of elements which is first increasing and then decreasing, find the maximum element in the array.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N, the size of array
The second line of each test case contains N integers which are the array elements.
Output:
Print the maximum element in the array.
Constraints:
1 = T = 50
3 = N = 100
1 = a[i] = 100000
Example:
Input
2
9
1 15 25 45 42 21 17 12 11
5
1 45 47 50 5
Output
45
50
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
int largest(int [],int ,int ) ;
int main()
{
int t,no,i ;
int arr[100] ;
cin>>t ;
while(t--)
{
cin>>no ;
for(i=0;i<no;i++)
cin>>arr[i] ;
cout<<largest(arr,0,no-1)<<endl ;
}
return 0;
}
int largest(int arr[],int beg,int last)
{
if(beg==last)
return arr[beg] ;
if(beg+1==last&&arr[beg]>=arr[last])
return arr[beg] ;
if(beg+1==last&&arr[beg]<arr[last])
return arr[last] ;
int mid=(beg+last)/2 ;
if(arr[mid]>=arr[mid+1]&&arr[mid]>=arr[mid-1])
return arr[mid] ;
if(arr[mid]>=arr[mid-1]&&arr[mid]<arr[mid+1])
return largest(arr,mid,last) ;
if(arr[mid]<arr[mid-1]&&arr[mid]>=arr[mid+1])
return largest(arr,beg,mid) ;
}
---------------------------------------------------------------------------------
Given an array of elements which is first increasing and then decreasing, find the maximum element in the array.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N, the size of array
The second line of each test case contains N integers which are the array elements.
Output:
Print the maximum element in the array.
Constraints:
1 = T = 50
3 = N = 100
1 = a[i] = 100000
Example:
Input
2
9
1 15 25 45 42 21 17 12 11
5
1 45 47 50 5
Output
45
50
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
int largest(int [],int ,int ) ;
int main()
{
int t,no,i ;
int arr[100] ;
cin>>t ;
while(t--)
{
cin>>no ;
for(i=0;i<no;i++)
cin>>arr[i] ;
cout<<largest(arr,0,no-1)<<endl ;
}
return 0;
}
int largest(int arr[],int beg,int last)
{
if(beg==last)
return arr[beg] ;
if(beg+1==last&&arr[beg]>=arr[last])
return arr[beg] ;
if(beg+1==last&&arr[beg]<arr[last])
return arr[last] ;
int mid=(beg+last)/2 ;
if(arr[mid]>=arr[mid+1]&&arr[mid]>=arr[mid-1])
return arr[mid] ;
if(arr[mid]>=arr[mid-1]&&arr[mid]<arr[mid+1])
return largest(arr,mid,last) ;
if(arr[mid]<arr[mid-1]&&arr[mid]>=arr[mid+1])
return largest(arr,beg,mid) ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment