Skip to content
Advertisement

i want to find the span of a array. Span is defined as difference of maximum value and minimum value [closed]

I tried by creating two functions for greatest and smallest values and then subtracting them .but the code doesn’t seem to work here’s the code.See if u could help me out .im new to java and still learning.

    import java.io.*;
import java.util.*;

public class Main{

public static void smler(int arr[],int j){
    for (int i=0;i<=j;j++){
        if(arr[i]<arr[i+1]){
        int temp =arr[i];
        arr[i]=arr[i+1];
        arr[i+1]=temp;
        }
    }
}
public static void grter(int arr[],int j){
    for (int i=0;i<=j;j++){
        if(arr[i]>arr[i+1]){
        int temp =arr[i];
        arr[i]=arr[i+1];
        arr[i+1]=temp;
    }
    }
}
public static void main(String[] args) throws Exception {
  Scanner sc= new Scanner (System.in);
  int n=sc.nextInt();
  int[] arr= new int[n];
  for(int i=0;i<=n;i++){
      arr[i]=sc.nextInt();
  }
  grter(arr,n);
 int y= arr[n];
 smler(arr,n);
 int z = arr[n];
 System.out.println(y-z);
 }
} 

Advertisement

Answer

There is an approach very similar to what you want to do.

   import java.io.*;
import java.util.*;

public class Main{

public static int smler(int arr[],int N){
    int smaller = arr[0];

    for (int i=1;i<N;i++){
        if(arr[i] < smaller){
          smaller = arr[i];
        }
    }

    return smaller;
}
public static int grter(int arr[],int N){
    int greater = arr[0];

    for (int i=0;i<N;i++){
        if(arr[i] > greater){
          greater = arr[i];
        }
    }
    
    return greater;
}

public static void main(String[] args) throws Exception {
  Scanner sc= new Scanner (System.in);
  int n=sc.nextInt();
  int[] arr= new int[n];
  for(int i=0;i<=n;i++){
      arr[i]=sc.nextInt();
  }
  
 System.out.println(grter(arr, n) - smler(arr, n));
 }
} 
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement