Dynamic Programming (Fibonacci series) --- robbers in the ring neighborhoods

In the ring robber robbery neighborhoods

213. House Robber II (Medium)

Subject description:

  Robber robbery in a ring-shaped block, but can not grab the neighboring residents, seeking the maximum amount of robbery.

Analysis of ideas:

  Because it is ring-shaped house, it means that the first houses and one house was close to the final. We can split into the annular array from 0 to numsSize-2, and one to two parts numsSzie-1, and then calculate the maximum number of robbery two parts, whichever is greater in the final as a result.

Code:

public  int rob(int []nums){
    if(nums==null||nums.length==0)
        return 0;
    int n=nums.length;
    if(n==1)
        return nums[0];
    return Math.max(help(0,n-2,nums),help(1,n-1,nums));
}
public int help(int start,int end,int []nums){
    int[]dp=new int[end-start+2];
    dp[0]=0;
    dp[1]=nums[start];
    for(int i=2;i<=(end-start+1);i++){
        dp[i]=Math.max(dp[i-1],dp[i-2]+nums[i-1+start]);
    }
    return dp[end-start+1];
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11116324.html