Calculate the maximum value of the addition of non-adjacent gold coins-Dynamic planning 1

Source: Internet
Author: User

The maximum value of the sum of the non-adjacent gold coins.

Enter the gold value of the N gold coins (positive custom) to find the maximum values of the gold coins that are not adjacent to each other.

Dynamic Planning Issues 1

Set f (n) to the maximum value of the nth gold number, F (0) =0,f (1) =a[1], and the input array starts with the subscript 1.

F (n) =max{a[n]+f (n-2), F (n-1)}.

The code is as follows:

ImportJava.util.Scanner; Public classJin_bi_zui_da_zhi { Public Static voidMain (string[] args) {Scanner sc=NewScanner (system.in); System.out.print ("Enter the number of coins N:"); intn=Sc.nextint (); inta[]=New int[N+1]; System.out.print ("Number of inputs N:");  for(inti=1;i<=n;++i) a[i]=Sc.nextint ();  Sc.close (); intmax=Hui (a,n); System.out.println (The maximum number of nonadjacent additions is: "+max);}; Public Static intHuiint[] A,intindex) {    intn=a.length; int[] f=New int[n]; f[0]=0; f[1]=a[1];  for(inti=2;i<=index;++i) {intM=a[i]+f[i-2]; intMax=m>f[i-1]?m:f[i-1]; F[i]=Max; }    returnf[index];};}

Calculate the maximum value of the addition of non-adjacent gold coins-Dynamic planning 1

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.