I am trying to find the Occurrences of a Maximum value in Integer Array.
e.g.
int[] ar = [3, 1, 2, 3];
Here, the Max 3
is repeated twice and so the expected output is 2
.
This works, I am getting count as 2
as the max value 3
occurred twice in the array
var max = int.MinValue;
var occurrenceCount = 0;
foreach(var x in ar)
{
if (x >= max) max = x;
}
foreach(var x in ar)
{
if (x == max) occurrenceCount++;
}
Output: 2 //occurrenceCount
With Linq
it's more simple,
var occurrenceCount = ar.Count(x => x == ar.Max())
Output: 2 //occurrenceCount
Now without Linq
, Is there any simplified or efficient way to do this?