# 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. – Ilkhd Sep 22 at 18:38
• It passed all of leetcode tests. But let me check what you are saying. – Gilad Sep 22 at 19:17
• @Ilkhd you are wrong my friend my code returns 25 – Gilad Sep 23 at 17:15
• Sorry, my fault. The code is a bit trickier than I thought. – Ilkhd Sep 23 at 21:21
• What happens if the input is int[] arr = {5, 5, 5, 5, 5, 5}; – Alex Leo Sep 26 at 14:17