Leetcode - House Robber

2235 단어
[제목] 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.
[분석]
1차원 동적 계획은num[i]에 대응하는 최대 안전 도금은 안전[i]이고 점차적으로는safe[i]=max(safe[i-1],safe[i-2]+num[i])라고 기록한다.
실현할 때 단지 하나의 삼원수 그룹만 순환해서 사용해야 한다.
// version1:  , ok, 
//  
public class Solution {
    public int rob(int[] num) {
        if (num == null || num.length == 0) 
            return 0;
        int safe = 0; // num[i-2]  ,num[i-2] 
        int adj = 0; // num[i-1] ,num[i-1] 
        int curr = 0; //  num[i] 
        int max = 0; // num[i] =max(curr, adj)
        for (int i = 0; i < num.length; i++) {
            curr = safe + num[i];
            if (curr > max)
                max = curr;
            safe = adj;
            adj = max;
        }
        return max;
    }
}
// version 2
//  :safe[i] = max(safe[i-1], safe[i-2] + num[i])
// safe[2] num[i] 
// safe[1] num[i-1], num[i] 
// safe[0] num[i-2] 
public class Solution {
     public int rob(int[] num) {
        if (num == null || num.length == 0) 
            return 0;
        int n = num.length;
        if (n == 1)
            return num[0];
        else if (n == 2)
            return num[0] > num[1] ? num[0] : num[1];
        
        int[] safe = {num[0], (num[1] > num[0]? num[1] : num[0]), 0};
        for (int i = 2; i < num.length; i++) {
            safe[2] = Math.max(safe[1], safe[0] + num[i]);
            safe[0] = safe[1];
            safe[1] = safe[2];
        }
        return safe[2];
     }
}

    

 

좋은 웹페이지 즐겨찾기