leetcode 198:House Robber

原创 2015年07月09日 01:24:41

题目:
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.
分析:
考察动态规划,在一条街上有很多房屋,每个房屋中都存放一定的现金,但是相邻房屋都被小偷光顾的话会引发报警系统,怎样才能在不引起报警的情况下偷到最多的现金。动态规划最重要的就是定义状态和状态转移方程。在这里试着定义状态为:”对第i个房屋的行为后最大获得的现金”,记为d[i],行为在这里就是偷或不偷。则状态转移方程可以为:d[i]=max{d[i-2]+nums[i],d[i-1]}
代码:

public class HouseRobber {
    public int rob(int[] nums){
        int len=nums.length;
        int odd = 0,even=0;
        for(int i=0;i<len;i++){
            if(i%2==0){
                odd=Math.max(odd+nums[i], even);
            }else{
                even=Math.max(even+nums[i],odd);
            }
        }
        return Math.max(odd, even);
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode#198. House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount...

leetcode 198 & 213:House Robber

一.House Robber I 的题意是:有一排商铺,强盗不能连续抢劫相邻的两家,否则会触动报警器,求强盗在不触动报警器的前提下,可以抢劫的最多金钱总和。(输入一维数组,从中选择若干个数,使得这些数...

LeetCode动态规划198. House Robber思路解析

LeetCode动态规划198. House Robber思路解析,用最容易理解的递归解释

leetcode 198 House Robber

今天看了一个华为西安研究院的一个女生代码大神的总结很有感悟,下面这句话送给大家:只有好的程序员才能写出人类可以理解的代码You are a professional robber planning t...

Leetcode 198. House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount...

Leetcode[198]-House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount...

Leetcode_198_House Robber

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/47680663 You are a profes...

LeetCode - 198. House Robber

每一个house都有rob和not rob两种状态,所以我们可以使用一个[n][2]的矩阵来记录每个房子被抢和不被抢的情况下所累计的钱的数量,这道动态规划问题的四要素如下: state: f[i][...

House Robber - LeetCode 198

题目描述: You are a professional robber planning to rob houses along a street. Each house has a certain...
  • bu_min
  • bu_min
  • 2015年04月24日 22:07
  • 287

[LeetCode]--198. House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode 198:House Robber
举报原因:
原因补充:

(最多只允许输入30个字)