(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:


猜你喜欢

转载自blog.csdn.net/scds_zyx/article/details/80172985
今日推荐