Maximum difference between number Pairs

Source: Internet
Author: User

In the array, subtract the number on the right of the number to get a number pair difference, and calculate the maximum value of the difference of all number pairs. For example, in the array {2, 4, 1, 16, 7, 5, 11, 9}, the maximum value of the number pair is 11, which is the result of 16 minus 5. In the above example, the maximum value of the number pair is 16-5, and for 5, 16 is the maximum value in its left-side sub-array, so you can traverse array a in sequence, find the maximum value of the left sub-array of the element whose current subscript is I, use this maximum value to subtract the current A [I] element, and record the difference value of the current number pair, compare the difference value with the number pair recorded earlier to determine whether to update the Code. The Code is implemented as follows:

1 int maxdiff (int * arr, int N) 2 {3 int Nmax = arr [0]; // The maximum value in the current array is 4 int nmaxdiff = 0; // The difference between the current maximum number pair is 5 Int ncurdiff = 0; // the difference between the maximum value and the element whose array subscript is I is 6 for (INT I = 1; I! = N; I ++) 7 {8 // update array Max 9 If (Nmax <arr [I-1]) 10 Nmax = arr [I-1]; 11 12 ncurdiff = Nmax-Arr [I]; 13 // update the maximum deviation between the number pairs ending with I in the array. 14 if (ncurdiff> nmaxdiff) 15 nmaxdiff = ncurdiff; 16} 17 18 return nmaxdiff; 19}

 

Maximum difference between number Pairs

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.