算法题——House Robber(JAVA)

题目描述:
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. 将原问题分解为子问题
把原问题分解为若干个子问题,子问题和原问题形式相同或类似,只不过规模变小了。 子问题的解一旦求出要被保存。
2.确定状态
在用动态规划解题时,我们往往将和子问题相关的各个变量的一组取值,称之为一个“状 态”。一个“状态”对应于一个或多个子问题, 所谓某个“状态”下的“值”,就是这个“状 态”所对应的子问题的解。
3.确定一些初始状态(边界状态)的值
4. 确定状态转移方程
定义出什么是“状态”,以及在该“状态”下的“值”后,就要找出不同的状态之间如何迁移――即如何从一个或多个“值”已知的 “状态”,求出另一个“状态”的“值”(递推公式)。

解题思路:
1. 将原问题分解为子问题

今天偷不偷

2.确定状态

每间房子可以有两个状态:偷或者不偷

3.确定一些边界状态

当走到最后一间房子的时候结束

4.确定状态转移方程

判断偷和不偷这件房子,那个收益大,将收益大的选作最佳方案

提交代码:

public class Solution {
    public int rob(int[] nums) {
        int rob = 0;
        int unrob = 0;
        int todayrob = 0;
        for (int i = 0; i < nums.length; i++) {
            //没偷前一家的情况下来偷这一家
            todayrob = unrob + nums[i];
            //不偷这一家的收益=max(没偷前一家,偷了前一家)
            unrob = unrob > rob ? unrob : rob;
            //偷这一家的收益
            rob = todayrob;
        }
        //目前最大收益=max(没偷最后一家,偷了最后一家)
        return unrob > rob ? unrob : rob;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值