Problem:
Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array. Note: the built-in Math.min(v1, v2) and Math.max(v1, v2) methods return the smaller or larger of two values.
bigDiff({10, 3, 5, 6}) → 7
bigDiff({7, 2, 10, 9}) → 8
bigDiff({2, 10, 7, 2}) → 8
Solution:
public int bigDiff(int[] nums) { int min = nums[0]; int max = nums[0]; for (int i = 0; i < nums.length; i++){ min = Math.min(min,nums[i]); max = Math.max(max,nums[i]); } return max-min; }
this is an alternative way to do it, by using more logic then a method;
ReplyDeletepublic int bigDiff(int[] nums) {
int max=nums[0];
int min=nums[0];
int temp=0;
for(int i=0; itemp){
max = nums[i];
temp=max;
}
}
for(int h=0; h<nums.length; h++){
if(nums[h]<temp){
min=nums[h];
temp=min;
}
}
return max-min;
}
Without the min/max method...
ReplyDeletepublic int bigDiff(int[] nums) {
int max=nums[0];
int min=nums[0];
for(int i=0;imax)
max=nums[i];
if(nums[i]<min)
min=nums[i];
}
return max-min;
}
Arrays.sort(nums);
ReplyDeleteint min=nums[0];
int max=nums[nums.length-1];
return max-min;
int max = Integer.MIN_VALUE;
ReplyDeleteint min = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
}
if (nums[i] < min) {
min = nums[i];
}
}
return max - min;
}
public int bigDiff(int[] nums) {
ReplyDeleteint max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
}
if (nums[i] < min) {
min = nums[i];
}
}
return max - min;
}
public int bigDiff(int[] nums) {
ReplyDeleteArrays.sort(nums);
return nums[nums.length-1] - nums[0];
}
int max=nums[0];
ReplyDeleteint min=nums[0];
for(int i=0; inums[i])
min=nums[i];
}return max-min;
public int bigDiff(int[] nums) {
ReplyDeleteint max=nums[0];
int min=nums[0];
for(int i=0; inums[i])
min=nums[i];
}return max-min;
}
public int bigDiff(int[] nums) {
ReplyDeleteint Max=0;
int Min=nums[0];
for(int i=0; i<nums.length; i++){
if(nums[i]<Min){
Min=nums[i];
}
}
for(int j=0; j<nums.length; j++){
Max=Math.max(Max, nums[j]);
}
return Max-Min;
}