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?
At least, you can merge the two first arrays. I would still use the Linq solution. It is clearer. If you really want to talk about performance read Which is faster? first.
So here is a O(n) solution:
int[] ar = {3, 1, 2, 3, 3, 4, 4};
int max = ar[0];
var occurrenceCount = 1;
for(var i = 1; i < ar.Length; i++)
{
if (ar[i] > max) {
max = ar[i];
occurrenceCount = 1;
}
else if (ar[i] == max) {
occurrenceCount++;
}
}
WriteLine(max);
WriteLine(occurrenceCount);