Be the first user to complete this post

  • 0
Add to List
Beginner

337. Find first two largest elements in a given array

Objective: Given an array of integers, write an algorithm to find the first two largest elements in the array.

Example:

Int [] a = {
6, 8, 1, 9, 2, 1, 10};

Output: 10,
9

Int [] a = {
6, 8, 1, 9, 2, 1, 10, 10};

Output: 10,
10

Int [] a = {6};
Output: Invalid Input, array size is less than 2

Approach:

  1. Take two variables; let’s call them first and second and mark them as -∞.
  2. Iterate through the array and for each element (let’s call it current), 
    • Compare it with the first and if first is less, assign the first value to second and assign current to first.
    • If above step is not true then current element might be a candidate of second highest element, so check if current>second,if yes then assign it to second.

See the code below for more understanding.

Output:

top two elements are: 10 9