How to find the Largest Difference in an Array
How to find the Largest Difference in an Array
Example
[7,1,5,3,6] -> 6 (7-1)
JAVA code
public static int getMaxDifferNumFromArray(int[] input) {
return getMaxFromArray(input) - getMinFromArray(input);
}
public static int getMaxFromArray(int[] input) {
int max = Integer.MIN_VALUE;
for (int temp : input) {
if (max < temp) {
max = temp;
}
}
return max;
}
public static int getMinFromArray(int[] input) {
int min = Integer.MAX_VALUE;
for (int temp : input) {
if (min > temp) {
min = temp;
}
}
return min;
}
the smallest element has to be before the biggest element
Example
[7,1,5,3,6] -> 5 (1-6)
JAVA code
public static int getMaxDifferNumSmallFirstFromArray(int[] input) {
int min = Integer.MAX_VALUE;
int rtn = 0;
int temp = 0;
for (int element : input) {
if (min < element) {
temp = element - min;
if (temp > rtn)
rtn = temp;
} else {
min = element;
}
}
return rtn;
}
the biggest element has to be before the smallest element
Example
[1,7,5,3,6] -> 4 (7-3)
JAVA code
public static int getMaxDifferNumBigFirstFromArray(int[] input) {
int max = Integer.MIN_VALUE;
int rtn = 0;
int temp = 0;
for (int element : input) {
if (max > element) {
element = max - element;
if (element > rtn)
rtn = element;
} else {
max = element;
}
}
return rtn;
}
0 개의 댓글:
댓글 쓰기