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.
You're overwriting the max and mins.
if (nums[i] > nums[j])
max = nums[i];
else if (nums[i] < nums[j])
min = nums[i];
}
You need to compare the current number with the max/min that is set already. Instead you're comparing the current number with another number, and then overwriting max/min if the condition is true. In this example, at one point 10 was the max, but then you later checked if(9>2)
, which is true, so you changed max = 10
to max = 9
.
Here it is in O(n^2) time, with the outer loop being completely useless.
public static int quadratic(int[] nums) {
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (nums[j] > max)
max = nums[j];
if (nums[j] < min)
min = nums[j];
}
}
System.out.println(max + " " + min);
int maxDifference = max - min;
return maxDifference;
}