Adjacent maximum difference, adjacent difference

Source: Internet
Author: User

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 };

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.