【題目描述】
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are?arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
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.
?Notice
This is an extension of?House Robber.
在上次打劫完一條街道之后,竊賊又發現了一個新的可以打劫的地方,但這次所有的房子圍成了一個圈,這就意味著第一間房子和最后一間房子是挨著的。每個房子都存放著特定金額的錢。你面臨的唯一約束條件是:相鄰的房子裝著相互聯系的防盜系統,且 當相鄰的兩個房子同一天被打劫時,該系統會自動報警。
給定一個非負整數列表,表示每個房子中存放的錢, 算一算,如果今晚去打劫,你最多可以得到多少錢 在不觸動報警裝置的情況下。
?注意事項
這題是House Robber的擴展,只不過是由直線變成了圈
【題目鏈接】
www.lintcode.com/en/problem/house-robber-ii/
【題目解析】
House Robber的延伸問題,將線性(linear)排列改成環形(cycle),DP的策略需要進行相應的調整,由于定義了不能選擇相鄰的房子,可以分別計算兩種情況,一個選擇nums[0],那么就不能選擇nums[nums.length],或者選擇nums[nums.length],就不可以選擇nums[0],這樣,環形的問題就分解成為兩個線性問題,最后取兩個結果中的最大值即可。
簡單的示例如下:
nums = [3,6,4]
第一種,選nums[0]
[3,6,X]
第二種,選nums[nums.length]
[X,6,4]
為了下標的標注方便,統一兩個DP數組的長度,只不過在最終的統計結果時,選nums[0]取DP數組的first[nums.length - 1], 而選nums[nums.length],則取DP數組中的second[nums.length]。
另外,因為是I的延伸題,I中所運用的DP可以被復用,只需要設定起始點和終點,那么問題II,就可以直接拆解為兩個不同起始點和終點的問題I。
【參考答案】