Given an array of integers, return the largest range, inclusive, of integers that are all included in the array. code example

Example 1: find the largest and smallest number in an unsorted integer array in Java

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Number of integers to enter:");
    int numberEnter = keyboard.nextInt();
    int numbers[] = new int[numberEnter];
    int pos = 0;
    do {
        System.out.printf("Please enter integer #%d/%d:%n", pos, numberEnter);
        numbers[pos++] = keyboard.nextInt();
    } while (pos < numberEnter && keyboard.hasNextInt());
    int min = numbers[0];
    int max = numbers[0];
    for (pos = 1; pos < numbers.length; pos++) {
        if (numbers[pos] < min) { // <-- test min.
            min = numbers[pos];
        }
        if (numbers[pos] > max) { // <-- test max.
            max = numbers[pos];
        }
    }
    // Display everything.
    System.out.printf("%s Min: %d Max: %d%n", Arrays.toString(numbers),
            min, max);
}

Example 2: largest subarray of 0's and 1's

public class Solution {

    public int findMaxLength(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        int maxlen = 0, count = 0;
        for (int i = 0; i < nums.length; i++) {
            count = count + (nums[i] == 1 ? 1 : -1);
            if (map.containsKey(count)) {
                maxlen = Math.max(maxlen, i - map.get(count));
            } else {
                map.put(count, i);
            }
        }
        return maxlen;
    }
}

Tags:

Misc Example