[LeetCode] House Robber II, leetcoderobber

Source: Internet
Author: User

[LeetCode] House Robber II, leetcoderobber

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. this time, all houses at this place are arranged in a circle. that means the first house is the neighbor of the last one. meanwhile, the security system for these houses remain the same as for those in the previous street.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

 

The biggest difference between this question and the previous basic edition is that all houses form a circle. Previously, we only need to consider whether the previous one of this house is rob or not. Now there are special cases.

The first and last houses cannot be both rob.

The simplest method is to call the first algorithm twice. (The first house in assume is rob, and the last house in assume is rob .)

Because nums. length-2 is available here, the special case should contain a separate algorithm when nums. length = 1.

The Code is as follows .~

public class Solution {    public int rob(int[] nums) {        if(nums.length==0||nums==null){            return 0;        }        return Math.max(rob1(nums,0,nums.length-2),rob1(nums,1,nums.length-1));                    }        private int rob1(int[]nums, int start,int end){         if(nums.length==0||nums==null){            return 0;         }         if(nums.length==1){             return nums[0];         }         int prerob=0;         int predontrob=0;         for(int i=start;i<end+1;i++){             int curr=predontrob+nums[i];             int dontcurr=Math.max(prerob,predontrob);             prerob=curr;             predontrob=dontcurr;         }         return Math.max(prerob,predontrob);             }}

 

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.