Learn-dsa..in 30 days!



























CC-20 : Search second largest number.

Description:

Given an input array, find the second largest number in the array.

Test cases and expected outputs:

Input Parameters Expected outputs
Array:
3, 22, 44, 67, 77, 96, 122, 144, 201,
Second largest number is 144

Pseudocode:

secondLargest(nums[]):

Integer array named nums is received as input parameters.
Set integer variable l1 to -1, we will use this variable to store largest number.
Set integer variable l2 to -1, , we will use this variable to store second largest number.
Iterate through nums using a for loop using idx as loop variable starting from 0 upto nums.length:
If (nums[idx] > l1) then:
Set l2=l1.
Set l1=nums[idx].
Else if nums[idx] < l1 and nums[idx]>l2 then:
Set l2=nums[idx].
Return l2.

Code:

public int secondLargest(int[] nums){
	int l1 =-1;
	int l2 =-1;
	for (int idx=0; idx < nums.length; idx++) {
		if (nums[idx] > l1) {
			l2=l1;
			l1=nums[idx];			
		} else if ((nums[idx] < l1)&&(nums[idx]> l2)){
			l2=nums[idx];
		}
	}
	return l2;
}

Click here to download and run code and test cases !