Home Software Engineering Most Completely different of Int-Array in Java

## The problem#

You could implement a perform that returns the distinction between the most important and the smallest worth in an inventory(lst) obtained as a parameter.

The checklist(`lst`) accommodates integers, which implies it might comprise some unfavorable numbers.

If the checklist is empty or accommodates a single aspect, `return 0`.

The checklist(`lst`) is just not sorted.

``````maxDiff([1, 2, 3, 4]); // return 3, as a result of 4 - 1 == 3
maxDiff([1, 2, 3, -4]); // return 7, as a result of 3 - (-4) == 7
``````

## The answer in Java code#

Choice 1:

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

Choice 2:

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

Choice 3:

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

## Take a look at circumstances to validate our answer#

``````import org.junit.Take a look at;
import static org.junit.Assert.*;
import org.junit.runners.JUnit4;

public class MaxDiffTest {

@Take a look at
public void BasicTests() {

assertEquals("solely positives", 4, Answer.maxDiff(new int[]{ 1, 2, 3, 4, 5, 5, 4 }));
assertEquals("solely negatives", 30, Answer.maxDiff(new int[]{ -4, -5, -3, -1, -31 }));
assertEquals("positives and negatives", 10, Answer.maxDiff(new int[]{ 1, 2, 3, 4, -5, 5, 4 }));
assertEquals("single aspect", 0, Answer.maxDiff(new int[]{ 1000000 }));