(LeetCode) T213. House Robber II

Problem:

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.


Before showing the solution of this problem,let's have a look at its easy vision.

T198. House Robber

The difference between these two problem is that the houses in  T198 are not arranged in a circle.

Let's see how to solve this problem.

Thought:

We can't rob the money from the houses that are neighbor,.So if we rob the money from one house,the house in front of it should be safe.So we have two situations.

when we go to one house, stl_be is that we haven't robbed the money in it, while stl_af is that we have robbed the money in it.

And when we go to a new house:

1. stl_be = max{stl_be, stl_af} [don't rob this time]

(At this the stl_be and stl_af are for the house before,so stl_be is that we wouldn't rob the money and stl_af is that we have robbed the money in the house before, so we can't rob for this time)

2.stl_af = stl_be + money[now] [rob this time]

(At this time we will rob the money, so stl_af will update to the sum of  stl_be for the house before and the money in the house now)

Update the stl_be and stl_af for every house except the first house,and we will get the newest data at last.

So the answer is max{stl_be, stl_af}

Solve:


And now we can solve the T213 with using the way in T198.

Thought:

In T213, the houses are arranged in a circle,so we can divide it into two part:house[1] to house[n-1] and house[2] to house[n].If there are n houses.

Solve:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值