关闭

【Leetcode】House Robber

2909人阅读 评论(0) 收藏 举报
分类:

题目链接:https://leetcode.com/problems/house-robber/

题目:

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.

思路:

用n数组表示到当前元素为止的最大值。则n[i]只跟n[i-2]和n[i-1]有关,当n[i-1]大于n[i-2]+nums[i]的时候可以放弃抢劫nums[i],因为抢了还不如不抢,且抢了i-2、i-1的情况下都可以抢劫i+1。

算法:

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


1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:515783次
    • 积分:8083
    • 等级:
    • 排名:第2491名
    • 原创:305篇
    • 转载:6篇
    • 译文:0篇
    • 评论:34条
    博客专栏
    文章分类
    最新评论