Monday, February 20, 2023
HomeSoftware EngineeringMost Totally different of Int-Array in Java

Most Totally different of Int-Array in Java


The problem

You have to implement a operate that returns the distinction between the most important and the smallest worth in a listing(lst) obtained as a parameter.

The listing(lst) incorporates integers, which implies it might include some unfavorable numbers.

If the listing is empty or incorporates a single factor, return 0.

The listing(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

Possibility 1:

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

Possibility 2:

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

Possibility 3:

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

Check circumstances to validate our resolution

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

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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments