Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Java 

Creating a Method to find Max Difference in an Array.

I can imagine many ways to do this but the simplest one I have is to simply sort the array in ascending order and then subtract the last element from the first.
Code
Arrays.sort(numbers);//Arrays.parallelSort(numbers);
return numbers[4] - numbers[0];//return numbers[numbers.length - 1] - numbers[0];


I don't know if performance would be better to manually find the largest and smallest or not. Sometimes the methods Oracle provides are more efficient.
In Java8 you can do
Code
public static int getMaxAd(int[] arr){
        return Arrays.stream(IntStream.range(0, arr.length - 1).toArray())
                  .map(x -> arr[x + 1] - arr[x])
                  .max().getAsInt();
    }

So
Code
int max = getMaxAd(numbers);


Possibly Related Threads...
Thread / Author Replies Views Last Post
by lilsergsApr 26, 2023 10:15 AM 0 116 Apr 26, 2023 10:15 AM
Last Post: lilsergs
[C] by gurlhackerclubMay 19, 2020 05:18 PM 8 260 May 19, 2020 05:18 PM
Last Post: k1r3n
[C] by SIM-2362662Apr 23, 2020 07:06 PM 11 375 Apr 23, 2020 07:06 PM
Last Post: dracx