Skip to content

164. Maximum Gap

Linjie Pan edited this page May 22, 2019 · 1 revision
public int maximumGap(int[] nums) {
    int max = 0; // the number of sort passes depends on the base of max element
    for(int i = 0; i < nums.length; i++)
        max = Math.max(nums[i], max);

    int divisor = 1;
    int temp[][] = new int[10][nums.length]; // save the elements in ten buckets
    int count[] = new int[10]; // count the size of each bucket
    
    while( divisor <= max ) { // sort the array
        for(int i = 0; i < nums.length; i++) { // put elements into corresponding bucket
            int index = (nums[i] / divisor) % 10;
            temp[index][count[index]] = nums[i];
            count[index]++;
        }

        int current = 0;
        for(int i = 0; i < 10; i++) { // update nums after each turn
            for(int j = 0; j < count[i]; j++) {
                nums[current++] = temp[i][j];
            }
            count[i] = 0;
        }

        divisor *= 10;
    }

    int result = 0;
    for(int i = 1; i < nums.length; i++)
        result = Math.max(nums[i] - nums[i - 1], result);

    return result;
}
Clone this wiki locally