House Robber I && II

4645 단어 &&
I
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
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.
 
public class Solution {

    public int rob(int[] num) {

 // https://leetcode.com/discuss/30020/java-o-n-solution-space-o-1  

    int prevNo = 0;

    int prevYes = 0;

    for (int n : num) {

        int temp = prevNo;

        prevNo = Math.max(prevNo, prevYes); // here prevNo is the next loop's prevNo

        prevYes = n + temp;                 // next loop's prevYes

    }

    return Math.max(prevNo, prevYes);



    }

}

II
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.
 
사고방식 발췌http://blog.csdn.net/xudli/article/details/45886721

하우스 로비 I의 업그레이드 버전입니다.첫 번째 요소와 마지막 요소가 동시에 나타날 수 없기 때문이다.콜 하우스 로비 I. 케이스 1: 마지막 요소는 포함되지 않습니다.case2: 첫 번째 요소는 포함되지 않습니다.
최대 값은 글로벌 최대입니다.
public class Solution {

    public int rob(int[] nums) {

        if(nums==null|| nums.length==0) return 0;

        if(nums.length<3) return Math.max(nums[0],nums[nums.length-1]);

        int pn=0, py= 0, r1=0, r2=0;

        for(int i=0;i<nums.length-1;i++){

            int tmp = pn;

            pn = Math.max(pn,py);

            py=nums[i]+tmp;

        }

        r1 = Math.max(pn,py);

        pn=0;

        py=0;

        for(int i=1;i<nums.length;i++){

            int tmp = pn;

            pn = Math.max(pn,py);

            py=nums[i]+tmp;

        }

        r2 = Math.max(pn,py);

        return Math.max(r1,r2);

    }

}

좋은 웹페이지 즐겨찾기