1. 程式人生 > >LeetCode: 213. House Robber II

LeetCode: 213. House Robber II

題目描述

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.

Example 1:

Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
             because they are adjacent houses.

Example 2:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

解題思路

參考 LeetCode: 198. House Robber 題解,計算區間 [0, size-1)(不偷最後一間) 和 [1, size) (不偷第一間)的最大值。

AC 程式碼

class Solution {
public:
    // [beg, end)
    int
rob(vector<int>& nums, int beg, int end) { // first: 當前房間不偷的最大收益 // second: 偷當前房間的最大收益 pair<int, int> lastHouse{0, 0}; pair<int, int> curHouse{0, 0}; for(size_t i = beg; i < end; ++i) { // 當前房間不偷:上一間房間不偷的最大收益和上間房間偷的最大收益的最大值 curHouse.first = max(lastHouse.second, lastHouse.first); // 偷當前房間:不偷上一間房間的最大收益加上偷當前房間的收益 curHouse.second = lastHouse.first + nums[i]; lastHouse = curHouse; } return max(curHouse.first, curHouse.second); } int rob(vector<int>& nums) { if(nums.empty()) { return 0; } else if(nums.size() == 1) { return nums[0]; } int moneyFirstRob = rob(nums, 0, nums.size()-1); int moneyLastRob = rob(nums, 1, nums.size()); return max(moneyFirstRob, moneyLastRob); } };