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
238765The 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).
123451All adjacent digits differ by exactly 1, so the maximum difference is 1.
919198The 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;
}This C solution works by:
- Reading the number as a string to easily access individual digits
- Iterating through the string starting from index 1
- For each character, calculating the absolute difference between the ASCII values of adjacent characters (which works because digits have consecutive ASCII values)
- Tracking the maximum difference found
- 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.