Maximum Different of Int-Array in Java


The challenge

You must implement a function that returns the difference between the biggest and the smallest value in a list(lst) received as a parameter.

The list(lst) contains integers, which means it may contain some negative numbers.

If the list is empty or contains a single element, return 0.

The list(lst) is not sorted.

maxDiff([1, 2, 3, 4]); // return 3, because 4 - 1 == 3
maxDiff([1, 2, 3, -4]); // return 7, because 3 - (-4) == 7

The solution in Java code

Option 1:

public class Solution {
  public static int maxDiff(int[] lst) {
    if (lst.length<2) return 0;
    java.util.Arrays.sort(lst);
    return lst[lst.length-1] - lst[0];
  }
}

Option 2:

import java.util.Arrays;
public class Solution {
  public static int maxDiff(int[] lst) {
    return lst.length == 0 ? 0 :
      Arrays.stream(lst).max().getAsInt() - Arrays.stream(lst).min().getAsInt();
  }
}

Option 3:

import static java.util.stream.IntStream.of;
class Solution {
  static int maxDiff(int[] lst) {
    if (lst.length < 2) return 0;
    var stats = of(lst).summaryStatistics();
    return stats.getMax() - stats.getMin();
  }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runners.JUnit4;

public class MaxDiffTest {
    
    @Test
    public void BasicTests() {
      
      assertEquals("only positives", 4, Solution.maxDiff(new int[]{ 1, 2, 3, 4, 5, 5, 4 }));
      assertEquals("only negatives", 30, Solution.maxDiff(new int[]{ -4, -5, -3, -1, -31 }));
      assertEquals("positives and negatives", 10, Solution.maxDiff(new int[]{ 1, 2, 3, 4, -5, 5, 4 }));
      assertEquals("single element", 0, Solution.maxDiff(new int[]{ 1000000 }));
      assertEquals("empty", 0, Solution.maxDiff(new int[]{}));
    } 
}