Topic
/* You is a professional robber planning to rob houses along a street. * Each house have a certain amount of money stashed, * the only constraint stopping all from robbing each of the them are th At * Adjacent houses has security system connected and * It would automatically contact the police if both adjacent Houses were broken into on the same night. * Given a list of non-negative integers representing the amount of money in each house, * Determine the maximum amount of Money you can rob tonight without alerting the police. */ /* */
Code
Dynamic Programming Method (emphasis)
1 //Dynamic Planning2 ImportJava.util.*;3 Public classMain {4 Public Static voidMain (string[] args) {5Scanner sc =NewScanner (system.in);6 intA =sc.nextint ();7 intAa[] =New int[a];8 for(inti=0;i<aa.length;i++){9Aa[i] =sc.nextint ();Ten } One if(aa.length==1){ ASystem.out.println (aa[0]); - return; - } the if(aa.length==2){ -System.out.println (Math.max (aa[0],aa[1])); - return; - } +AA[2] + = aa[0]; - if(aa.length==3){ +System.out.println (Math.max (aa[2), aa[3])); A return; at } - for(inti=3;i<aa.length;i++){ -Aa[i] + = Math.max (aa[i-2), aa[i-3]); - } -System.out.println (Math.max (aa[aa.length-1), aa[aa.length-2])); - } in}
Analytical
The problem of optimal solution can be solved by dynamic programming algorithm.
Dynamic Programming Algorithm:
1. The global optimal solution must contain a local optimal solution, but it does not necessarily contain the previous local optimal solution, so all the previous optimal solutions need to be recorded.
2. The key to dynamic programming is the state transition equation, that is, how to derive the global optimal solution from the local optimal solution.
3. Boundary conditions: The simplest, locally optimal solution that can be directly derived
State transfer equation: aa[i] + = Math.max (Aa[i-2], aa[i-3]); (i>=4)
Because the two adjacent cannot be calculated together, the final and second-to-last size are compared to the optimal solution.
"Java algorithm problem" professional robbery