Method getMaxEvenOdd
returns the maximum amount by which the number of even elements exceeds the number of odd elements during a left to right traversal of arr
. The method returns 0
if the number of even elements never exceeds the number of odd elements.
getMaxEvenOdd
examples
int[] arr1 = new int[] {4, 6, 1, 4, 3, 4, 4, 7};
// index: 0 1 2 3 4 5 6 7
// even - odd: 1 2 1 2 1 2 3 2
System.out.println(MaxEvenOdd.getMaxEvenOdd(arr1)); // prints 3
int[] arr2 = new int[] { 5, 7, 2, 5, 4, 3, 3, 8};
// index: 0 1 2 3 4 5 6 7
// even - odd: -1 -2 -1 -2 -1 -2 -3 -2
System.out.println(MaxEvenOdd.getMaxEvenOdd(arr2)); // prints 0
For each array, the number under each index represents the difference between the number of even elements and the number of odd elements up to and including the element at that index. A positive number indicates more even elements.
There are 3 even elements and 1 odd element up to and including the value at arr1[3]
. There are 5 even elements and 2 odd elements up to and including the value at arr1[6]
.
There are 2 even elements and 3 odd elements up to and including the value at arr2[4]
.
getMaxEvenOdd(arr1)
returns 3
because the difference between the number of even and odd elements reaches 3 after visiting the element at index 6.
getMaxEvenOdd(arr2)
returns 0
because the number of even elements never exceeds the number of odd elements.
getMaxEvenOdd
method & explanation
public static int getMaxEvenOdd(int[] arr)
{
int difference = 0;
int maxDifference = 0;
for(int i = 0; i < arr.length; i++)
{
if(arr[i] % 2 == 0)
difference++;
else
difference--;
if(difference > maxDifference)
maxDifference = difference;
}
return maxDifference;
}
difference
stores the difference between the number of known even values and the number of known odd values. A positive number indicates more even values.
maxDifference
stores the maximum known difference, or 0
if the number of even values has never exceeded the number of odd values.
Initializing maxDifference
to 0
is appropriate for several reasons.
0
is the first thing that could be the maximum.- Initializing
maxDifference
to0
ensures that the conditionaldifference > maxDifference
evaluates totrue
for the first desired maximum. - Initializing
maxDifference
to0
works for the special case in which which the number of even values never exceeds the number of odd values. The conditiondifference > maxDifference
only evaluates totrue
for positive values ofdifference
.
Navigation
- Find the min/max
- Find the min/max in an array of objects
- Find the min/max of a fixed number of values
- Find the min/max of values accepted as input