Find the second maximum number in the array with the least complexity

Tried to destroy him, but no luck. How to find the second maximum number in the array with the least complexity ?

The code OR idea will be very useful.

I can iterate over the array and see the maximum number after that I have the maximum number, and then loop the array again to find the second one in the same way.

But surely this is not effective.

+6
source share
16 answers

You can sort the array and select an element in the second index, but the next O (n) loop will be much faster.

int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 }; int largest = int.MinValue; int second = int.MinValue; foreach (int i in myArray) { if (i > largest) { second = largest; largest = i; } else if (i > second) second = i; } System.Console.WriteLine(second); 

OR

Try this (using LINQ):

 int secondHighest = (from number in test orderby number descending select number).Distinct().Skip(1).First() 

How to get the second highest number in an array in Visual C #?

+19
source
 public static int F(int[] array) { array = array.OrderByDescending(c => c).Distinct().ToArray(); switch (array.Count()) { case 0: return -1; case 1: return array[0]; } return array[1]; } 
+1
source
  static void Main(string[] args) { int[] myArray = new int[] { 0, 11, 2, 15, 16, 8, 16 ,8,15}; int Smallest = myArray.Min(); int Largest = myArray.Max(); foreach (int i in myArray) { if(i>Smallest && i<Largest) { Smallest=i; } } System.Console.WriteLine(Smallest); Console.ReadLine(); } 

This will work even if you have a reputation for items in the array

0
source
  int[] arr = {-10, -3, -3, -6}; int h = int.MinValue, m = int.MinValue; foreach (var t in arr) { if (t == h || t == m) continue; if (t > h) { m = h; h = t; } else if(t > m ) { m = t; } } Console.WriteLine("High: {0} 2nd High: {1}", h, m); //or, m = arr.OrderByDescending(i => i).Distinct().Skip(1).First(); Console.WriteLine("High: {0} 2nd High: {1}", h, m); 
0
source

Answer in C #:

 static void Main(string[] args) { //let us define array and vars var arr = new int[]{ 100, -3, 95,100,95, 177,-5,-4,177,101 }; int biggest =0, secondBiggest=0; for (int i = 0; i < arr.Length; ++i) { int arrItem = arr[i]; if(arrItem > biggest) { secondBiggest = biggest; //always store the prev value of biggest //to second biggest... biggest = arrItem; } else if (arrItem > secondBiggest && arrItem < biggest) //if in our //iteration we will find a number that is bigger than secondBiggest and smaller than biggest secondBiggest = arrItem; } Console.WriteLine($"Biggest Number:{biggest}, SecondBiggestNumber: {secondBiggest}"); Console.ReadLine(); //make program wait } 

Conclusion: the greatest number: 177, the second BiggestNumber: 101

0
source
 /* we can use recursion */ var counter = 0; findSecondMax = (arr)=> { let max = Math.max(...arr); counter++; return counter == 1 ? findSecondMax(arr.slice(0,arr.indexOf(max)).concat(arr.slice(arr.indexOf(max)+1))) : max; } console.log(findSecondMax([1,5,2,3,0])) 
0
source
 static void Main(string[] args){ int[] arr = new int[5]; int i, j,k; Console.WriteLine("Enter Array"); for (i = 0; i < 5; i++) { Console.Write("element - {0} : ", i); arr[i] = Convert.ToInt32(Console.ReadLine()); } Console.Write("\nElements in array are: "); j=arr[0]; k=j; for (i = 1; i < 5; i++) { if (j < arr[i]) { if(j>k) { k=j; } j=arr[i]; } } Console.WriteLine("First Greatest element: "+ j); Console.WriteLine("Second Greatest element: "+ k); Console.Write("\n"); } 
0
source

It doesn't look like your structure is a tree ... It's just a simple array, right?

The best solution is to sort the array. And depending on the top or bottom, display the second or second last item, respectively.

Another alternative is to use some built-in methods to get the initial max. Run this item and then search for the maximum again. I do not know C #, therefore I can not give a direct code.

-1
source

You want to sort the numbers, and then just take the second largest. Here is a fragment without regard to efficiency:

 var numbers = new int[] { 3, 5, 1, 5, 4 }; var result=numbers.OrderByDescending(x=>x).Distinct().Skip(1).First(); 
-1
source
 namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int size; Console.WriteLine("Enter the size of array"); size = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the element of array"); int[] arr = new int[size]; for (int i = 0; i < size; i++) { arr[i] = Convert.ToInt32(Console.ReadLine()); } int length = arr.Length; Program program = new Program(); program.SeconadLargestValue(arr, length); } private void SeconadLargestValue(int[] arr, int length) { int maxValue = 0; int secondMaxValue = 0; for (int i = 0; i < length; i++) { if (arr[i] > maxValue) { secondMaxValue = maxValue; maxValue = arr[i]; } else if(arr[i] > secondMaxValue) { secondMaxValue = arr[i]; } } Console.WriteLine("First Largest number :"+maxValue); Console.WriteLine("Second Largest number :"+secondMaxValue); Console.ReadLine(); } } } 
-1
source

I give a solution that in JavaScript, the complexity of o (n / 2) is required to determine the highest and second highest number.
Fiddler Link works here

  var num=[1020215,2000,35,2,54546,456,2,2345,24,545,132,5469,25653,0,2315648978523]; var j=num.length-1; var firstHighest=0,seoncdHighest=0; num[0] >num[num.length-1]?(firstHighest=num[0],seoncdHighest=num[num.length-1]):(firstHighest=num[num.length-1], seoncdHighest=num[0]); j--; for(var i=1;i<=num.length/2;i++,j--) { if(num[i] < num[j] ) { if(firstHighest < num[j]){ seoncdHighest=firstHighest; firstHighest= num[j]; } else if(seoncdHighest < num[j] ) { seoncdHighest= num[j]; } } else { if(firstHighest < num[i]) { seoncdHighest=firstHighest; firstHighest= num[i]; } else if(seoncdHighest < num[i] ) { seoncdHighest= num[i]; } } } 
-1
source

It's not so bad:

 int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 }; var secondMax = myArray.Skip(2).Aggregate( myArray.Take(2).OrderByDescending(x => x).AsEnumerable(), (a, x) => a.Concat(new [] { x }).OrderByDescending(y => y).Take(2)) .Skip(1) .First(); 

It is quite low in complexity since it is only for all species with a maximum of three elements

-1
source

My solution is below.

  class Program { static void Main(string[] args) { Program pg = new Program(); Console.WriteLine("*****************************Program to Find 2nd Highest and 2nd lowest from set of values.**************************"); Console.WriteLine("Please enter the comma seperated numbers : "); string[] val = Console.ReadLine().Split(','); int[] inval = Array.ConvertAll(val, int.Parse); // Converts Array from one type to other in single line or Following line // val.Select(int.Parse) Array.Sort(inval); Console.WriteLine("2nd Highest is : {0} \n 2nd Lowest is : {1}", pg.Return2ndHighest(inval), pg.Return2ndLowest(inval)); Console.ReadLine(); } //Method to get the 2nd lowest and 2nd highest from list of integers ex 1000,20,-10,40,100,200,400 public int Return2ndHighest(int[] values) { if (values.Length >= 2) return values[values.Length - 2]; else return values[0]; } public int Return2ndLowest(int[] values) { if (values.Length > 2) return values[1]; else return values[0]; } } 
-1
source

Array sorting and transition from second to last value?

-2
source
  var result = (from elements in inputElements orderby elements descending select elements).Distinct().Skip(1).Take(1); return result.FirstOrDefault(); 
-2
source
 namespace FindSecondLargestNumber { class Program { static void Main(string[] args) { int max=0; int smax=0; int i; int[] a = new int[20]; Console.WriteLine("enter the size of the array"); int n = int.Parse(Console.ReadLine()); Console.WriteLine("elements"); for (i = 0; i < n; i++) { a[i] = int.Parse(Console.ReadLine()); } for (i = 0; i < n; i++) { if ( a[i]>max) { smax = max; max= a[i]; } else if(a[i]>smax) { smax=a[i]; } } Console.WriteLine("max:" + max); Console.WriteLine("second max:"+smax); Console.ReadLine(); } } } 
-2
source

All Articles