find the maximum element in an array which is first increasing and then decreasing _ geeksforgeeks

14
5/12/12 Find the maximum element in an array which is first increasing and then decreasing | GeeksforGeeks 1/14 www.geeksforgeeks.org/archives/17028 GeeksforGeeks A computer science portal for geeks Home Q&A Interview Corner Ask a question Feedback Contribute About us Subscribe Arrays Articles Bit Magic C/C++ Puzzles GFacts Linked Lists MCQ Misc Output Strings Trees Find the maximum element in an array which is first increasing and then decreasing January 14, 2012 Given an array of integers which is initially increasing and then decreasing, find the maximum value in the array. Input: arr[] = {8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1} Output: 500 Input: arr[] = {1, 3, 50, 10, 9, 7, 6} Output: 50 Corner case (No decreasing part) Input: arr[] = {10, 20, 30, 40, 50} Output: 50

Upload: niraj-kumar

Post on 29-Jul-2015

62 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Find the Maximum Element in an Array Which is First Increasing and Then Decreasing _ GeeksforGeeks

5/12/12 Find the maximum element in an array which is first increasing and then decreasing | GeeksforGeeks

1/14www.geeksforgeeks.org/archives/17028

GeeksforGeeks

A computer science portal for geeks

HomeQ&AInterview CornerAsk a question

FeedbackContributeAbout us

SubscribeArraysArticlesBit MagicC/C++ PuzzlesGFactsLinked ListsMCQMiscOutputStringsTrees

Find the maximum element in an array which is firstincreasing and then decreasing

January 14, 2012

Given an array of integers which is initially increasing and then decreasing, find the maximumvalue in the array.

Input: arr[] = {8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1}Output: 500

Input: arr[] = {1, 3, 50, 10, 9, 7, 6}Output: 50

Corner case (No decreasing part)Input: arr[] = {10, 20, 30, 40, 50}Output: 50

Page 2: Find the Maximum Element in an Array Which is First Increasing and Then Decreasing _ GeeksforGeeks

5/12/12 Find the maximum element in an array which is first increasing and then decreasing | GeeksforGeeks

2/14www.geeksforgeeks.org/archives/17028

Corner case (No increasing part)Input: arr[] = {120, 100, 80, 20, 0}Output: 120

Method 1 (Linear Search)We can traverse the array and keep track of maximum and element. And finally return themaximum element.

Time Complexity: O(n)

Method 2 (Binary Search)We can modify the standard Binary Search algorithm for the given type of arrays.i) If the mid element is greater than both of its adjacent elements, then mid is the maximum.ii) If mid element is greater than its next element and smaller than the previous element thenmaximum lies on left side of mid. Example array: {3, 50, 10, 9, 7, 6}iii) If mid element is smaller than its next element and greater than the previous element thenmaximum lies on right side of mid. Example array: {2, 4, 6, 8, 10, 3, 1}

#include <stdio.h> int findMaximum(int arr[], int low, int high){ int max = arr[low]; int i; for (i = low; i <= high; i++) { if (arr[i] > max) max = arr[i]; } return max;} /* Driver program to check above functions */int main(){ int arr[] = {1, 30, 40, 50, 60, 70, 23, 20}; int n = sizeof(arr)/sizeof(arr[0]); printf("The maximum element is %d", findMaximum(arr, 0, n-1)); getchar(); return 0;}

#include <stdio.h>

Page 3: Find the Maximum Element in an Array Which is First Increasing and Then Decreasing _ GeeksforGeeks

5/12/12 Find the maximum element in an array which is first increasing and then decreasing | GeeksforGeeks

3/14www.geeksforgeeks.org/archives/17028

Time Complexity: O(Logn)

This method works only for distinct numbers. For example, it will not work for an array like{0, 1, 1, 2, 2, 2, 2, 2, 3, 4, 4, 5, 3, 3, 2, 2, 1, 1}.

int findMaximum(int arr[], int low, int high){ /* Base Case: Only one element is present in arr[low..high]*/ if (low == high) return arr[low]; /* If there are two elements and first is greater then the first element is maximum */ if ((high == low + 1) && arr[low] >= arr[high]) return arr[low]; /* If there are two elements and second is greater then the second element is maximum */ if ((high == low + 1) && arr[low] < arr[high]) return arr[high]; int mid = (low + high)/2; /*low + (high - low)/2;*/ /* If we reach a point where arr[mid] is greater than both of its adjacent elements arr[mid-1] and arr[mid+1], then arr[mid] is the maximum element*/ if ( arr[mid] > arr[mid + 1] && arr[mid] > arr[mid - 1]) return arr[mid]; /* If arr[mid] is greater than the next element and smaller than the previous element then maximum lies on left side of mid */ if (arr[mid] > arr[mid + 1] && arr[mid] < arr[mid - 1]) return findMaximum(arr, low, mid-1); else // when arr[mid] is greater than arr[mid-1] and smaller than arr[mid+1] return findMaximum(arr, mid + 1, high);} /* Driver program to check above functions */int main(){ int arr[] = {1, 3, 50, 10, 9, 7, 6}; int n = sizeof(arr)/sizeof(arr[0]); printf("The maximum element is %d", findMaximum(arr, 0, n-1)); getchar(); return 0;}

Page 4: Find the Maximum Element in an Array Which is First Increasing and Then Decreasing _ GeeksforGeeks

5/12/12 Find the maximum element in an array which is first increasing and then decreasing | GeeksforGeeks

4/14www.geeksforgeeks.org/archives/17028

Please write comments if you find anything incorrect, or you want to share more informationabout the topic discussed above.

You may also like following posts

1. Search an element in a sorted and pivoted array2. Check for Majority Element in a sorted array3. Given an array arr[], find the maximum j – i such that arr[j] > arr[i]4. Maximum and minimum of an array using minimum number of comparisons5. Find a Fixed Point in a given array

20 comments so far

1. jk says:March 23, 2012 at 10:04 AM

Send 2people

int max(int a, int b){return (a > b) ? a : b;} int maxElementRec(int* array, int startIndex, int endIndex){ if(startIndex == endIndex) return array[startIndex]; if(array[startIndex] > array[startIndex + 1]) return array[startIndex]; if(array[endIndex] > array[endIndex - 1]) return array[endIndex]; int midIndex = (startIndex + endIndex)/2; if(array[midIndex] > array[midIndex - 1] && array[midIndex] > array[midIndex + 1]) if(array[midIndex] > array[midIndex - 1] || array[midIndex] < array[midIndex + 1]) if(array[midIndex] < array[midIndex - 1] || array[midIndex] > array[midIndex + 1]) return max(maxElementRec(array, startIndex, midIndex - 1), maxElementRec(array, midIndex + 1, endIndex));} int maxElement(int* array, int size){ return maxElementRec(array, 0, size - 1);} int main(){ int arr[] = {0, 1, 1, 2, 2, 2, 2, 2, 3, 4, 4, 5, 5, 3, 3, 2, 2, 1, 1}; printf("%d\n", maxElement(arr, 19));

Page 5: Find the Maximum Element in an Array Which is First Increasing and Then Decreasing _ GeeksforGeeks

5/12/12 Find the maximum element in an array which is first increasing and then decreasing | GeeksforGeeks

5/14www.geeksforgeeks.org/archives/17028

Reply2. kartikaditya says:

February 20, 2012 at 3:39 AM

}

public class MaxInIncAndDec { private static int getMaxInIncAndDec(int a[], int start, int if (start > end) { return Integer.MIN_VALUE; } int mid = (start + end) >> 1; while (start < end) { if (a[mid] > a[mid + 1]) { end = mid; } else if (a[mid] < a[mid + 1]) { start = mid + 1; } else { int leftMax = getMaxInIncAndDec(a, start, mid - 1); int rightMax = getMaxInIncAndDec(a, mid + 1, end); if (leftMax == Integer.MIN_VALUE) { return rightMax; } if (rightMax == Integer.MIN_VALUE) { return leftMax; } return (leftMax > rightMax) ? leftMax : rightMax; } mid = (start + end) >> 1; } return a[mid]; } public static int getMaxInIncAndDec(int a[]) { return getMaxInIncAndDec(a, 0, a.length - 1); } public static void main(String args[]) { System.out.println(getMaxInIncAndDec(new int[]{8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1})); System.out.println(getMaxInIncAndDec(new int[]{1, 3, 50, 10, 9, 7, 6})); System.out.println(getMaxInIncAndDec(new int[]{10, 20, 30, 40, 50})); System.out.println(getMaxInIncAndDec(new int[]{120, 100, 80, 20, 0})); System.out.println(getMaxInIncAndDec(new int[]{0, 1, 1, 2, 2, 2, 2, 2, 3, 4, 4, 5, 3, 3, 2, 2, 1, 1})); }}

Page 6: Find the Maximum Element in an Array Which is First Increasing and Then Decreasing _ GeeksforGeeks

5/12/12 Find the maximum element in an array which is first increasing and then decreasing | GeeksforGeeks

6/14www.geeksforgeeks.org/archives/17028

Reply3. Krishs says:

January 27, 2012 at 6:36 PM

Well simple enough ...

Replykartik says:January 27, 2012 at 11:49 PM

This looks similar to method 1 (linear search). Time complexity of this would beO(n).

Reply4. Wayne says:

January 24, 2012 at 12:40 AM

If the array elements aren't necessarily distinct, then in the extreme case, all elementsare the same. Method 2 would degrade to O(N) solution since you have to scan bothsides linearly until you meet anything breaking the even.

Reply5. sandeep says:

January 18, 2012 at 5:13 PM

what if the numbers are repeated.like (0 1 1 2 2 2 2 2 3 4 4 5 3 3 2 2 1 1) and you findmid whose left and right both element are equal to mid how will you decide which partto check.. left or right?

ReplyGeeksforGeeks says:January 18, 2012 at 9:51 PM

int max_ ( int arr[] , int len ) { int index = 0 ; for( index = 0; index < len ; index++ ) { if( index != (len -1) && arr[index] > arr[index+1] ) { } return arr[len-1]; }

/* Paste your code here (You may delete these lines if not writing code) */

Page 7: Find the Maximum Element in an Array Which is First Increasing and Then Decreasing _ GeeksforGeeks

5/12/12 Find the maximum element in an array which is first increasing and then decreasing | GeeksforGeeks

7/14www.geeksforgeeks.org/archives/17028

@sandeep: Thanks for pointing out this case. The method 2 doesn't always workif there are duplicates in array. We have added the same to the original post.Keep it up!

ReplyShreyas says:January 30, 2012 at 11:27 AM

@Sandeep:they said increasing and then decreasing so no duplicates allowed. 1 2 3 0 -1 butcan never be 1 2 2 3.

Reply6. shaan7 says:

January 17, 2012 at 11:43 AM

Why not start from the beginning and when you find a number less than previousnumber, the previous number is max?

ReplyNithish says:January 17, 2012 at 2:01 PM

@shaan: That would have a worst case complexity of o(N). Consider the examplegiven in the problem itself - Input: arr[] = {10, 20, 30, 40, 50}.

Replyshaan7 says:January 17, 2012 at 2:41 PM

Ah yes, my bad, actually I was suggesting an improvement for Method1.

Replyabbie says:February 17, 2012 at 1:09 PM

@Nithish: since the array is first increasing and then decreasing so weneed not to compare all the elements in Method 1, the moment wefind any element greater than current max element we can stop theiteration in Method 1. It'll reduce the no of comparisons though it'llnot improve the complexity that much.

Correct me if I am wrong. Thanx

/* Paste your code here (You may delete these lines if not writing code) */

Page 8: Find the Maximum Element in an Array Which is First Increasing and Then Decreasing _ GeeksforGeeks

5/12/12 Find the maximum element in an array which is first increasing and then decreasing | GeeksforGeeks

8/14www.geeksforgeeks.org/archives/17028

Reply7. Priyanka says:

January 17, 2012 at 12:39 AM

Replygowtham says:February 12, 2012 at 10:02 AM

Replygowtham says:February 12, 2012 at 10:06 AM

i am new here so correct me if i am wrong. @priyanka you have used m

8. Ankur says:

#include<stdio.h>#define n 8void main(){int a[n];int l=0,i,h=n-1,m;for(i=0;i<n;i++)scanf("%d",&a[i]);while(l<=h){ m=(l+h)/2; if(m==n-1) break; else if(a[m]>a[m+1] && a[m]>a[m-1] && m<n-1 && m>0) break; else if(a[m]<a[m+1] && m<n-1) l=m+1; else if(a[m]>a[m+1] && m<n-1) h=m-1;}printf("%d",a[m]);}

i am new here so correct me if i am wrong. @priyanka you have used m<n-1 in every

<p></p> <div class="reply"> <a class="comment-reply-link" href="17028?replytocom=7479#respond"

Page 9: Find the Maximum Element in an Array Which is First Increasing and Then Decreasing _ GeeksforGeeks

5/12/12 Find the maximum element in an array which is first increasing and then decreasing | GeeksforGeeks

9/14www.geeksforgeeks.org/archives/17028

January 16, 2012 at 3:19 AM

Iterative code below which is easier to understand

Reply9. flyinghearts says:

January 15, 2012 at 8:13 PM

Reply10. sachin says:

January 15, 2012 at 5:24 AM

This will not will for

int findMaximum(int a[], int n){ int low=0; int high=n-1; int mid; while(low<=high){ mid=low+(high-low)/2; if((mid==0 || a[mid-1]<a[mid]) && (mid==n-1 || a[mid]>a[mid+1])){ cout<<a[mid]<<" "; return a[mid]; }/*Increasing Part of Array*/ else if((mid==0 || a[mid-1]<a[mid]) && (mid==n-1 || a[mid]<a[mid+1])){ cout<<a[mid]<<" "; low=mid+1; }/*Decreasing Part of Array */ else if((mid==0 || a[mid-1]>a[mid]) && (mid==n-1 || a[mid]>a[mid+1])) high=mid-1; }}

int findMaximum(const int arr[], size_t len){ assert(len > 0); size_t low = 0, high = len - 1; while (low != high) { size_t mid = low + (high - low) / 2; if (arr[mid] < arr[mid + 1]) low = mid + 1; else high = mid; } return arr[low];}

Page 10: Find the Maximum Element in an Array Which is First Increasing and Then Decreasing _ GeeksforGeeks

5/12/12 Find the maximum element in an array which is first increasing and then decreasing | GeeksforGeeks

10/14www.geeksforgeeks.org/archives/17028

int[] a = {10,15,20,12,5,6,25};It will return 20 instead of 25

ReplyNithish says:January 15, 2012 at 5:51 AM

@sachin: The question reads - "Given an array of integers which is initiallyincreasing and then decreasing,...". So your input is not for this question.

Replysachin says:January 15, 2012 at 5:55 AM

Ohh I see ! thanks nitish

Reply

Comment

Name (Required) Email (Required)

Website URI Your Comment (Writing code? please paste your

code between sourcecode tags)

[sourcecode language="C"]/* Paste your code here (You may delete these lines if not writing code) */[/sourcecode]

Have Your Say

/* Paste your code here (You may delete these lines if not writing code) */

/* Paste your code here (You may delete these lines if not writing code) */

/* Paste your code here (You may delete these lines if not writing code) */

Page 11: Find the Maximum Element in an Array Which is First Increasing and Then Decreasing _ GeeksforGeeks

5/12/12 Find the maximum element in an array which is first increasing and then decreasing | GeeksforGeeks

11/14www.geeksforgeeks.org/archives/17028

Search

Popular Tags

GATEJavaDynamic ProgrammingBacktrackingPattern SearchingDivide & ConquerGraphOperating SystemsRecursion

Popular Posts

All permutations of a given stringMemory Layout of C ProgramsUnderstanding “extern” keyword in CMedian of two sorted arraysTree traversal without recursion and without stack!Structure Member Alignment, Padding and Data PackingIntersection point of two Linked ListsLowest Common Ancestor in a BST.Check if a binary tree is BST or notSorted Linked List to Balanced BST

Page 12: Find the Maximum Element in an Array Which is First Increasing and Then Decreasing _ GeeksforGeeks

5/12/12 Find the maximum element in an array which is first increasing and then decreasing | GeeksforGeeks

12/14www.geeksforgeeks.org/archives/17028

250 Subscribe

Forum Latest Discussion

LIS in nlogn timeLast Post By: kartik

Inside: Interview Questions

tree to fileLast Post By: Dheeraj

Inside: Interview Questions

Page 13: Find the Maximum Element in an Array Which is First Increasing and Then Decreasing _ GeeksforGeeks

5/12/12 Find the maximum element in an array which is first increasing and then decreasing | GeeksforGeeks

13/14www.geeksforgeeks.org/archives/17028

Count internal nodes in a binary treeLast Post By: kartik

Inside: Interview Questions

Ancestor of two given leaf nodesLast Post By: dead

Inside: Trees specific questions

combine elements of an array, so as to minimize weights.Last Post By: rohanag

Inside: Interview Questions

FB interview questionLast Post By: ranganath111

Inside: Interview Questions

Testing of factorial of a numberLast Post By: rukawa

Inside: Interview Questions

numeric puzzleLast Post By: asm

Inside: Algorithms

Forum Categories

Interview QuestionsC/C++ Programming QuestionsAlgorithmsTrees specific questionsLinked List specific questionsMultiple Choice QuestionsObject oriented queriesGPuzzles

Page 14: Find the Maximum Element in an Array Which is First Increasing and Then Decreasing _ GeeksforGeeks

5/12/12 Find the maximum element in an array which is first increasing and then decreasing | GeeksforGeeks

14/14www.geeksforgeeks.org/archives/17028

Operating SystemsMiscellaneousJava specific QuestionsPerl specific Questions

Recent Comments

Venki on Structure Member Alignment, Padding and Data Packingavi on Structure Member Alignment, Padding and Data Packingatul on A Program to check if strings are rotations of each other or notVenki on Structure Member Alignment, Padding and Data Packingrahul on Dynamic Programming | Set 13 (Cutting a Rod)Sandeep on Dynamic Programming | Set 3 (Longest Increasing Subsequence)Yueming on Dynamic Programming | Set 3 (Longest Increasing Subsequence)avi on Structure Member Alignment, Padding and Data Packing

@geeksforgeeks, Some rights reservedPowered by WordPress & MooTools, customized by geeksforgeeks team