Sort by

recency

|

1119 Discussions

|

  • + 0 comments

    This is the code in java

    Difference(int[] elements){
        this.elements = elements;
    
    }
    
    public void  computeDifference(){
       int smallest = 101;
       int largest = 0;
    
        for(int i = 0; i < elements.length; i++){
            if(elements[i] > largest){
                largest = elements[i];
            }
            if(elements[i] < smallest){
                smallest = elements[i];
            }
        }
        maximumDifference = largest - smallest;
    
    
    }
    
  • + 0 comments

    Can someone explain to me while the following code only returns zeroes (JAVA):

    public int computeDifference(){ Arrays.sort(elements); int len = elements.length-1;

        int maximumDifference = Math.abs(elements[0] - elements[len]);
        return maximumDifference;
    }
    
  • + 0 comments

    C#

        public Difference(int[] elements)
        {
            this.elements = elements;
            this.maximumDifference = 0;
        }
    
        public int computeDifference()
        {
            Array.Sort(elements);
            
            //getting max and min values and getting the abs difference of them
            maximumDifference = Math.Abs(elements[0] - elements[elements.Length-1]);
            
            return maximumDifference;
        }
    
  • + 0 comments

    JAVA SOLUTION

    class Difference { private int[] elements; public int maximumDifference;

    // Add your code here
    public Difference(int[] elements){
        this.elements = elements;
    }
    
    public void computeDifference(){        
        Arrays.sort(elements);
    
        int min = Arrays.stream(elements).min().getAsInt();
        int max = Arrays.stream(elements).max().getAsInt();
        maximumDifference = max - min;
    
    }
    

    }

  • + 0 comments

    Two solutions, one as intended and one smarter solution based off of the constraints

    `
    Difference(int[] elements){ this.elements = elements; this.maximumDifference = Integer.MIN_VALUE; }

    // Add your code here
     int computeDifference(){
        for (int i = 0; i < elements.length; i++){
            for(int j = 0; j< elements.length;j++){
                int currentDiff = Math.abs(elements[i] - elements[j]);
                if (maximumDifference < currentDiff){
                    maximumDifference = currentDiff;
                }
            }
        }
        return maximumDifference;
    }
    
    Difference(int[] elements){
        this.elements = elements;
        this.maximumDifference = Integer.MIN_VALUE;
    }
    
    // Add your code here
     int computeDifference(){
        int min = elements[0];
        int max = elements[0];
        for (int num : elements) {
            if (num < min) min = num;
            if (num > max) max = num;
        }
        maximumDifference = max - min;
        return maximumDifference;
    }