Largest Two Elements – Single Loop

Problem

Given an array of positive integers. Find the first and second largest elements in the array. You are not allowed to use more than one loop in your solution.

Solution

The solution is to use a single loop to find the first and second maximum. The current array element is compared to both first and second maximum values calculated so far then updating them accordingly. Please refer to the code below for more details. In the next post we will solve this problem using divide and conquer technique.

Code

Here is the C++ code to do that using a single loop

Tags:
One Comment

Add a Comment

Your email address will not be published. Required fields are marked *