Title Description:
The maximum difference between any two elements in an unordered array, and the number of groups with the largest difference.
Input:
The input consists of two lines, the first line entering an integer n, and the second row n positive integers separated by a space.
Output:
The output is a row that contains the maximum difference and the number of groups that exist.
Sample input:
4
4 1 2 1
Output:
3 2
One implementation code is as follows (Java edition):
1 ImportJava.util.Scanner;2 /**3 * The maximum difference of any two elements in an unordered array in O (n) time complexity, and the number of groups that exist4 * @authorJiajoa5 *6 */7 Public classmain{8 Public Static voidMain (String args[]) {9Scanner cin =NewScanner (system.in);Ten intn =cin.nextint (); One int[] v =New int[n]; A for(inti=0;i<n;i++){ -V[i] =cin.nextint (); - } the GetResult (n,v); - cin.close (); - } - + Public Static voidGetResult (intNint[] b) { - intmin = Integer.max_value;//Record Minimum value + intmax = Integer.min_value;//Record Maximum value A intMincount = 0;//record the minimum number of values at intMaxCount = 0;//record the maximum number of values - for(inti=0;i<n;i++){ - if(b[i]==max) { -maxcount++; - } - if(b[i]>max) { inMax =B[i]; -MaxCount = 1; to } + - if(b[i]==min) { themincount++; * } $ if(b[i]<min) {Panax NotoginsengMin =B[i]; -Mincount = 1; the } + } A the intMAXB = Max-min;//maximum difference of two numbers in an array + intCount = Maxcount*mincount;//number of groups with maximum difference - $System.out.println (maxb+ "" +count); $ } -}
Finding the maximum difference of any two elements in an unordered array in O (n) time complexity, and the number of groups that exist