# LeetCode: House Robber II C#

https://leetcode.com/problems/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),
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.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace CirucularArray
{
/// <summary>
/// https://leetcode.com/problems/house-robber-ii/
/// </summary>
[TestClass]
{
[TestMethod]
public void RobberTestEvenArray()
{
int[] arr = {1, 2, 3, 4, 5, 1};
int result = Rob(arr);
Assert.AreEqual(9, result);

}
[TestMethod]
public void RobberTestOddArray()
{
int[] arr = { 5, 1, 2, 10 ,5 };
int result = Rob(arr);
Assert.AreEqual(15, result);

}

[TestMethod]
public void TestMethodOneItem()
{
int[] arr = {1 };
int result = Rob(arr);
Assert.AreEqual(1, result);
}

public int Rob(int[] nums)
{
if (nums == null || nums.Length == 0)
{
return 0;
}

if (nums.Length == 1)
{
return nums;
}

return Math.Max(Helper(0, nums.Length - 2,nums), Helper(1, nums.Length - 1,nums));
}

private int Helper(int start, int end, int[] nums)
{
int prevMax = 0;
int currMax = 0;
for (int i = start; i <= end; i++)
{
int temp = currMax;
currMax = Math.Max(prevMax + nums[i], currMax);
prevMax = temp;
}

return currMax;
}
}
}

• But your solution is not correct; try this: 11 1 2 4 1 10 1. The right result is 11 + 4 + 10 = 25. Your code would output 11 + 2 + 1 = 14. Sep 22, 2019 at 18:38
• It passed all of leetcode tests. But let me check what you are saying. Sep 22, 2019 at 19:17
• @Ilkhd you are wrong my friend my code returns 25 Sep 23, 2019 at 17:15
• Sorry, my fault. The code is a bit trickier than I thought. Sep 23, 2019 at 21:21
• What happens if the input is int[] arr = {5, 5, 5, 5, 5, 5}; Sep 26, 2019 at 14:17

Here is another version of a solution

 public int Rob(int[] nums)
{
int n = nums.Length;
if (n == 0)
{
return 0;
}
if (n == 1)
{
return nums;
}
int[] dp = new int[n];
int[] dp2 = new int[n];
dp = nums;
dp = Math.Max(nums, nums);

dp2 = 0; //we "SKIP" nums
dp2 = nums;

for (int i = 2; i < n; i++)
{
dp[i] = Math.Max(nums[i] + dp[i - 2], dp[i - 1]);
dp2[i] = Math.Max(nums[i] + dp2[i - 2], dp2[i - 1]);
}
//for dp we can't use n-1 since it is next to nums so we only use n-2
return Math.Max(dp[n - 2], dp2[n - 1]);

}