Codechef : Problem name " Largest and Second Largest " solution in C#
===========================Problem Statement==========================
You are given an array of integers.
Find the maximum sum of two distinct integers in the array.
Note: It is guaranteed that there exist at least two distinct integers in the array.
Input Format
- The first line of input will contain a single integer , denoting the number of test cases.
- Each test case consists of multiple lines of input.
- The first line of each test case contains single integer — the size of the array.
- The next line contains space-separated integers, denoting the array .
Output Format
For each test case, output on a new line, the maximum sum of two distinct integers in the array.
===================================Solution====================================
using System;
using System.Linq;
public class Test
{
public static void Main()
{
int t=Convert.ToInt32(Console.ReadLine());
for(int i=0;i<t;i++){
int N=Convert.ToInt32(Console.ReadLine());
string[] array=Console.ReadLine().Split(' ');
int[] arInt= new int[N];
for(int h=0; h<array.Length;h++)
{
arInt[h]=Convert.ToInt32(array[h]);
}
Array.Sort(arInt);
int[] arInt2=arInt.Distinct().ToArray();
Console.WriteLine(arInt2[arInt2.Length-1]+arInt2[arInt2.Length-2]);
// will not work if have duplicates
//array.sort methos use
}
}
}
===================================Explanation=============================
First we are taking input array , as we know that will be an string array
After that we convert that string array into integer array, so that we can perform array functions
We will sort the array using the inbuilt method Sort, which will sort array in ascending order
Then we will remove all the duplicates because it will be noise in our calculations.
Finally we will print the sum of last and second last element because those elements are the largest and the second largest
Comments
Post a Comment