Is it possible to find the second maximum number from an array of integers by traversing the array only once?
As an example, I have a array of five integers from whi
How about the following below. make_heap is O(n) so this is efficient and this is 1-pass We find the second max by taking advantage that it must be one of the heap children of the parent, which had the maximum.
#include
#include
int main()
{
int arr[6]={0,1,2,3,4,5};
std::make_heap(arr, arr+6);
std::cout << "First Max: " << arr[0] << '\n';
std::cout << "Second Max: " << std::max(arr[1], arr[2]) << '\n';
return 0;
}