In: Computer Science
In the class MyArray, write a method named indexAndCountOfMax that on an input array of numbers, finds and returns (1) the smallest index of the largest element of the array and (2) the number of times the largest element occurs in the array. The header of the method should be public static int[ ] indexAndCountOfMax (double[ ] A). The method should return an array of length 2, where the value at index 0 is the smallest index of the largest element of ?, and the value at index 1 is the number of times the largest element occurs in ?. For example, if ? = [1, 4, 2, 3, 4, 4, 3], then indexAndCountOfMax (A) should return [1, 3] because the largest element of ? is 4, the smallest index where it occurs is 1, and it occurs 3 times in the array (at indices 1, 4 and 5).
public class MyArray{
public static int[ ] indexAndCountOfMax (double[ ]
A)
{
int[] result = new int[2];
result[0] = 0; //let 1st element be
largest
result[1] = 1; //it occurs
once
for(int i = 1; i < A.length;
i++){
if(A[i] ==
A[result[0]]) //largest appearing again
result[1]++; //increment count
else if(A[i]
> A[result[0]]) //new largest
{
//update index and count
result[0] = i;
result[1] = 1;
}
}
return result;
}
}