easy
0 views

Find Largest Difference Between Two Adjacent Digits

Find the maximum absolute difference between any two adjacent digits in a given number.

Understand the Problem

Problem Statement

Given an integer N, find the largest absolute difference between any two adjacent digits in the number.

This problem is useful in numerical analysis for understanding the volatility or variation within a number's digit sequence, with applications in data analysis, fraud detection, and signal processing.

Constraints

  • 10 <= N <= 10^9
  • N is a positive integer
  • The number has at least 2 digits
  • All digits are between 0 and 9

Examples

Example 1
Input
23876
Output
5
Explanation

The differences between adjacent digits are: |3-2| = 1, |8-3| = 5, |7-8| = 1, |6-7| = 1. The largest difference is 5 (between digits 8 and 3).

Example 2
Input
12345
Output
1
Explanation

All adjacent digits differ by exactly 1, so the maximum difference is 1.

Example 3
Input
91919
Output
8
Explanation

The differences are: |1-9| = 8, |9-1| = 8, |1-9| = 8, |9-1| = 8. The maximum difference is 8.

Solution

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char n[10];
    scanf("%s", n);
    
    int max_diff = 0;
    for(int i = 1; i < strlen(n); i++) {
        int diff = abs(n[i] - n[i-1]);
        if(diff > max_diff) {
            max_diff = diff;
        }
    }
    
    printf("%d", max_diff);
    return 0;
}
Time:O(d) where d is the number of digits in the input
Space:O(d) for storing the string representation of the number
Approach:

This C solution works by:

  1. Reading the number as a string to easily access individual digits
  2. Iterating through the string starting from index 1
  3. For each character, calculating the absolute difference between the ASCII values of adjacent characters (which works because digits have consecutive ASCII values)
  4. Tracking the maximum difference found
  5. Outputting the result

The approach leverages the fact that digit characters '0' through '9' have consecutive ASCII values, so subtracting their ASCII codes gives the same result as subtracting the actual digits.

Visual Explanation

Loading diagram...