How to find the maximum difference between two successive elements in an int list with Java

1 Answer

0 votes
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Main {
    public static int maximumGap(List<Integer> lst) {
        int gap = 0;

        if (lst.size() == 0) {
            return 0;
        }

        // Sort the vector in ascending order
        Collections.sort(lst);

        int size = lst.size();

        for (int i = 0; i < size - 1; i++) {
            // Calculate the difference between consecutive elements
            int diff = lst.get(i + 1) - lst.get(i);

            if (diff > gap) {
                gap = diff;
            }
        }

        // Return the largest gap
        return gap;
    }

    public static void main(String[] args) {
        List<Integer> lst = Arrays.asList(1, 3, 5, 9, 11, 13); // 5, 9 -> 4

        System.out.println(maximumGap(lst));
    }
}



/*
run:
 
4
 
*/

 



answered Jan 8, 2025 by avibootz
...