The title above sums up my question, to clarify things an example is:
array[0] = 1
array[1] = 3
array[2] = 7 // largest
array[3] = 5
so the result I would like is 2, since it contains the largest element 7.
Given an array, find the largest element in it. Example: The solution is to initialize max as first element, then traverse the given array from second element till end. For every traversed element, compare it with max, if it is greater than max, then update max.
To get the index of the max value in an array: Get the max value in the array, using the Math.max () method. Call the indexOf () method on the array, passing it the max value. The indexOf method returns the index of the first occurrence of the value in the array or -1 if the value is not found.
Declare an indexes variable that stores an empty array. Iterate over the array and push only the indexes of the max values to the indexes array. We used a for loop to iterate for array.length iterations. On each iteration, we check if the element at that index is the max value, and if it is, we push the current index to the indexes array.
The following code shows how to get the index of the max value in a one-dimensional NumPy array: The argmax () function returns a value of 2. This tells us that the value in index position 2 of the array contains the maximum value.
int maxAt = 0;
for (int i = 0; i < array.length; i++) {
maxAt = array[i] > array[maxAt] ? i : maxAt;
}
Another functional implementation
int array[] = new int[]{1,3,7,5};
int maxIndex =IntStream.range(0,array.length)
.boxed()
.max(Comparator.comparingInt(i -> array[i]))
.map(max->array[max])
.orElse(-1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With