JetBrains Academy: Finding max and min in arrays - Kamil-Jankowski/Learning-JAVA GitHub Wiki
JetBrains Academy: Finding max and min in arrays
Find the max in an array:
Implement a method to find the max in an array of ints. The input arrays always contain at least one number.
public static int findMax(int[] numbers) {
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
return max;
}
Find the min in an array:
Implement a method to find the min in an array of ints. The input arrays always contain at least one number.
public static int findMin(int[] numbers) {
int min = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
return min;
}
Find the index of the first min in an array:
Implement a method to find the index of the first min in an array of ints. If the input array is empty, the method should return -1
.
public static int findIndexOfMin(int[] numbers) {
if (numbers.length == 0) {
return -1;
}
int minIndex = 0;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < numbers[minIndex]) {
minIndex = i;
}
}
return minIndex;
}
Find index of the last max in an array:
Implement a method to find the index of the last max in an array of ints. If the input array is empty, the method should return -1
.
public static int findIndexOfLastMax(int[] numbers) {
if (numbers.length == 0) {
return -1;
}
int lastMaxIndex = 0;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] >= numbers[lastMaxIndex]) {
lastMaxIndex = i;
}
}
return lastMaxIndex;
}
Find the index of K min in an array:
Implement a method that finds the index of the K-th element equal to the minimum in an array of ints. If no such element can be found, return -1
. The input array can be empty, K > 0
.
public static int findIndexOfKMin(int[] numbers, int k) {
if (numbers.length == 0) {
return -1;
}
int min = numbers[0];
int indexOfKMin = -1;
int counter = 0;
//finding minimum value of the array
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
//finding minimum k-th element in the array
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == min) {
counter++;
if (counter == k) {
indexOfKMin = i;
break;
}
}
}
return indexOfKMin;
}
Find the second largest element in an array:
Implement a method to find the second largest number in an array of ints.
If the input array is empty or contains only a single number, the method must return Integer.MIN_VALUE
.
If the input array contains multiple largest elements, consider them as the same value.
public static int findSecondLargestNumber(int[] numbers) {
if (numbers.length <= 1) {
return Integer.MIN_VALUE;
}
int max = numbers[0];
int max2 = Integer.MIN_VALUE;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max2 = max;
max = numbers[i];
} else if (numbers[i] == max) {
continue;
} else if (numbers[i] > max2) {
max2 = numbers[i];
}
}
return max2;
}