Adjacent maximum difference, adjacent difference
Adjacent maximum difference question description
Design an algorithm with the complexity of O (n) to calculate the maximum difference between adjacent elements after sorting in an unordered array.
Given an integer ArrayAAnd array sizeNReturns the maximum difference value. Make sure that the number of array elements is greater than or equal to 2 and less than or equal to 500.
Test example:
[9,3,1,10],4
Return Value: 6
Bucket sorting + discretization
1 class MaxDivision {2 public: 3 int findMaxDivision (vector <int> A, int n) {4 // write code here 5 // The thought of Bucket sorting and discretization 6 int minv = A [0], maxv = A [0]; 7 for (int I = 0; I <n; I ++) {8 if (A [I]> maxv) maxv = A [I]; 9 if (A [I] <minv) minv = A [I]; 10} 11 if (minv = maxv) return 0; 12 int size = maxv-minv + 1; 13 int a [size]; 14 for (int I = 0; I <size; I ++) {15 a [I] = 0; 16} 17 for (int I = 0; I <n; I ++) {18 a [A [I]-minv] = 1; 19} 20 int sum = 0; 21 int ans = 0; 22 for (int I = 0; I <size; I ++) {23 if (a [I] = 0) sum ++; 24 if (a [I] = 1) sum = 0; 25 if (sum> ans) ans = sum; 26} 27 return ans + 1; 28} 29 };