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.
Note: Please do not use any string methods. No sorting allowed. No additional data structures including arrays allowed.
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).
Here is my solution. Is it possible to combine the loops?
int max;
int min;
int maxCount = 0;
int minCount = 0;
if (a.length > 2) {
max = a[0];
min = a[0];
} else {
return 0;
}
for (int num : a) {
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
for (int num : a) {
if (max == num) {
maxCount++;
}
if (min == num) {
minCount++;
}
}
if (maxCount == minCount) {
return 1;
}
return 0;