Java > Array-2 > bigDiff (CodingBat Solution)

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;

}

9 comments:

  1. this is an alternative way to do it, by using more logic then a method;

    public 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;


    }

    ReplyDelete
  2. Without the min/max method...

    public 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;

    }

    ReplyDelete
  3. Arrays.sort(nums);
    int min=nums[0];
    int max=nums[nums.length-1];
    return max-min;

    ReplyDelete
  4. int 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;
    }

    ReplyDelete
  5. public int bigDiff(int[] nums) {
    int 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;
    }

    ReplyDelete
  6. public int bigDiff(int[] nums) {

    Arrays.sort(nums);

    return nums[nums.length-1] - nums[0];

    }

    ReplyDelete
  7. int max=nums[0];
    int min=nums[0];
    for(int i=0; inums[i])
    min=nums[i];
    }return max-min;

    ReplyDelete
  8. public int bigDiff(int[] nums) {
    int max=nums[0];
    int min=nums[0];
    for(int i=0; inums[i])
    min=nums[i];
    }return max-min;

    }

    ReplyDelete
  9. public int bigDiff(int[] nums) {
    int 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;
    }

    ReplyDelete