House Robber【打家劫舍】【容易】

一、题目

英文: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.

中文: 题目大意:你是一名专业强盗,计划沿着一条街打家劫舍。每间房屋都储存有一定数量的金钱,唯一能阻止你打劫的约束条件就是:由于房屋之间有安全系统相连,如果同一个晚上有两间相邻的房屋被闯入,它们就会自动联络警察,因此不可以打劫相邻的房屋。 
给出一个非负数的整数组,代表每个房子的钱数,确保今晚你可以抢劫的最大金额而不报警。

、代码

java代码

public int rob(int[] num) {//数组表示各个房子的金额 int prevNo = 0;//不抢劫当前房子,则得到的最大金额 int prevYes = 0;//抢劫当前房子,则得到的最大金额 for (int n : num) { int temp = prevNo; prevNo = Math.max(prevNo, prevYes);//不偷当前房子,则当前最大金额为上一次 偷和不偷 之间的最大值 prevYes = n + temp;//偷,则当前最大金额是上一次 不偷(已知必须发生的前提)的值加上当前房子的值 } return Math.max(prevNo, prevYes); }

另一种形式的代码:
public int rob(int[] num) { int rob = 0; //max monney can get if rob current house int notrob = 0; //max money can get if not rob current house for(int i=0; i

你可能感兴趣的:(Dynamic)