Find second largest pair
First find 3 largest numbers and the sum of first and third integer is the 2nd largest number.
The size of Array should be greater than 3.
public class FindSecondLargestPair {
public static void main(String args[]) {
int[] nums = {-1, 3, 5, -6, 8, -9, 10, 4, -2, 7};
secondLargestPair(nums, nums.length);
}
public static void secondLargestPair(int[] arr, int arr_size) {
int i, first, second, third;
/* There should be atleast three elements */
if (arr_size < 3)
{
System.out.print(" Invalid Input ");
return;
}
third = first = second = Integer.MIN_VALUE;
for (i = 0; i < arr_size ; i ++)
{
/* If current element is greater than
first*/
if (arr[i] > first)
{
third = second;
second = first;
first = arr[i];
}
/* If arr[i] is in between first and
second then update second */
else if (arr[i] > second)
{
third = second;
second = arr[i];
}
else if (arr[i] > third)
third = arr[i];
}
System.out.println("Three largest elements are " +
first + " " + second + " " + third);
System.out.println("Second Largest Sum-->"+ (first+third));
}
}
Comments
Post a Comment