Typical problem of dynamic programming 03: Maximum number-to-Number Difference (or minimum number-to-Number Difference) in the array)

Source: Internet
Author: User

Question: In the array, subtract the number on the right of the number to get a number pair. Calculate the maximum value of the difference between 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.

Reference: http://zhedahht.blog.163.com/blog/static/2541117420116135376632/

Forum: http://stackoverflow.com/questions/11858790/find-the-largest-possible-difference-in-an-array-with-the-smaller-integer-occuri

[Analysis] top-down analysis, where diff [I] records 0 ~ Max [I] records 0 ~ The maximum number of I, the State recursive equation is:

Diff [I + 1] = math. Max (MAX [I]-array [I + 1], diff [I])

For bottom-up analysis, the first test is Max [1] = 2, diff [1] = 2-4 =-2. Max [2] = 4, diff [2] = max (4-1, diff [1]) = 3. Max [3] = 4, diff [3] = max (4-16, diff [2]) = 3 .......

The algorithm complexity is O (n ).

/*** Creation Time: 5:27:46, January 1, September 5, 2014 * Project name: test * @ author Cao yanfeng * @ since JDK 1.6.0 _ 21 * class description: dynamic Programming resolves the maximum number of pairs in the array */public class maxdiffofarray {/*** @ paramargs */public static void main (string [] ARGs) {// todo auto-generated method stub int [] array = {, 0,-1}; system. out. println (getmaxdiff (array);} public static int getmaxdiff (INT [] array) {int length = array. length; If (length = 1) {return-999;} If (length = 2) {return array [2]-array [1];} int max = array [0]; int maxdiff = max-array [1]; for (INT I = 2; I <length; I ++) {If (array [1]> MAX) {max = array [I-1];} int currentdif = max-array [I]; If (currentdif> maxdiff) {maxdiff = currentdif ;}} return maxdiff ;}}


Typical problem of dynamic programming 03: Maximum number-to-Number Difference (or minimum number-to-Number Difference) in the array)

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.