House Robber II

题目
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, 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.

答案

class Solution {
    public int rob_sequence(int[] nums) {
        int n = nums.length;
        if(n == 0) return 0;
        // Define f[i][0] to mean: max number of coins we can steal from house i...n-1 (if we don't steal from i)
        // Define f[i][1] to mean: max number of coins we can steal from house i...n-1 (if we steal from i)
        
        int[][] f = new int[n][2];
        f[n - 1][0] = 0;
        f[n - 1][1] = nums[n - 1];
        
        for(int i = n - 2; i >= 0; i--) {
            f[i][0] = Math.max(f[i + 1][0], f[i + 1][1]);
            f[i][1] = f[i + 1][0] + nums[i];
        }
        return Math.max(f[0][0], f[0][1]);
    }
    
    public int rob(int[] nums) {
        int n = nums.length;
        if(n == 0) return 0;
        if(n == 1) return nums[0];
        
        
        int[] A = new int[n - 1];
        for(int i = 0; i < n - 1; i++) A[i] = nums[i];
        int ret1 = rob_sequence(A);
        
        for(int i = 1; i < n; i++) A[i - 1] = nums[i];
        int ret2 = rob_sequence(A);
        return Math.max(ret1, ret2);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容