I have an array int [] nums = {5, 1, 6, 10, 4, 7, 3, 9, 2}
I want to find the distance between the smallest and largest number in that array in O(n^2) time. It needs to be O(n^2) time as per the requirements of the assignment. To do this, I am writing a method called quadratic
. So far I have come up with the code below.
public static int quadratic(int[] nums) {
int max = nums[0];
int min = nums[0];
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (nums[i] > nums[j])
max = nums[i];
else if (nums[i] < nums[j])
min = nums[i];
}
}
int maxDifference = max - min;
return maxDifference;
}
The problem is, when I run that method with array mentioned above, I get a max difference of 0. I expect 9, since the largest number is 10, and the smallest is 1. 10 - 1 = 9.
My question is, can someone show me how I can change my code so that it properly computes the max distance between the smallest and largest numbers?