Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to find the max number in an array

Tags:

c++

algorithm

This is an interview question There is an array of integers. The elements in the array can follow the following patterns.

  1. numbers are in ascending order
  2. numbers are in descending order
  3. numbers increases in the beginning and decreases in the end
  4. numbers decreases in the beginning and increases in the end

What is the efficient way to find the max number in the array?

like image 779
cppcoder Avatar asked Jul 19 '11 04:07

cppcoder


1 Answers

In that case, all you need to do is to determine whether it's (3). If not, the answer is max(first, last).

In the case that all elements are equal, you'll need to exhaustively search the array to show that there's not one high number somewhere in the middle. So I think it's O(n) to determine whether you're in (3).

like image 104
Patrick87 Avatar answered Oct 14 '22 07:10

Patrick87