Question:
An array is defined to be maxmin equal if it contains at least two different elements and the number of
times the maximum value occur is the same as the number of times the minimum
value occur. So {11, 4, 9, 11, 8, 5 , 4, 10} is maxmin equal, because the max value 11 and
min value 4 both appear two times in the array.
Write a function called isMaxMinEqual
that accepts an integer array and returns 1 if the array is maxmin equal; otherwise it returns 0.
If you are programming in
Java or C#, the function signature is
int isMaxMinEqual(int[ ] a)
If you are programming in C
or C++, the function signature is
int isMaxMinEqual(int a[ ], int len) where len
is the number of elements in the array
Some other examples:
if the input array is
|
isMaxMinEqual should
return
|
{}
|
0 (array must have at
least two different elements)
|
{2}
|
0 (array must have at
least two different elements)
|
{1, 1, 1, 1, 1, 1}
|
0 (array must have at
least two different elements)
|
{2, 4, 6, 8, 11}
|
1 (Both max value (11)
and min value 2 appear exactly one time)
|
{-2, -4, -6, -8, -11}
|
1 (Both max value (-2)
and min value -11 appear exactly one time)
|
public static int isMaxMinEqual(int[] a)
{
int max = a[0],
min = a[0],
maxCount = 0,
minCount = 0;
if (a.Length < 2)
return 0;
for (int i = 0; i < a.Length; i++)
{
if (max < a[i])
{
max = a[i];
maxCount = 1;
}
else if (min > a[i])
{
min = a[i];
minCount = 1;
}
else
{
if (max == a[i])
{
maxCount++;
}
if (min == a[i])
{
minCount++;
}
}
}
if (maxCount == minCount && max != min)
{
return 1;
}
else
{
return 0;
}
}
0 comments:
Post a Comment