Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0beeecd

Browse files
authored
198 and 213 house robber.
1 parent 3fe1f13 commit 0beeecd

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

198-House-Robber.cs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
using System;
2+
namespace AlgoPractice
3+
{
4+
public class Solution
5+
{
6+
public int Rob(int[] nums)
7+
{
8+
if (nums == null || nums.Length == 0)
9+
{
10+
return 0;
11+
}
12+
else if (nums.Length == 1)
13+
{
14+
return nums[0];
15+
}
16+
17+
var rob1 = 0;
18+
var rob2 = 0;
19+
foreach (var n in nums)
20+
{
21+
var temp = Math.Max(rob1 + n, rob2);
22+
rob1 = rob2;
23+
rob2 = temp;
24+
}
25+
return rob2;
26+
}
27+
}
28+
}
29+

213-House-Robber-II.cs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
using System;
2+
namespace AlgoPractice
3+
{
4+
public class Solution
5+
{
6+
public int Rob(int[] nums)
7+
{
8+
var startFromHouse1 = RobHelper(nums, 0, nums.Length - 2);
9+
var startFromHouse2 = RobHelper(nums, 1, nums.Length - 1);
10+
var result = Math.Max(startFromHouse1, startFromHouse2);
11+
return result;
12+
}
13+
14+
public int RobHelper(int[] num, int start, int end)
15+
{
16+
var rob1 = 0;
17+
var rob2 = 0;
18+
for(var i = start; i<= end; i++)
19+
{
20+
var temp = Math.Max(rob1 + num[i], rob2);
21+
rob1 = rob2;
22+
rob2 = temp;
23+
}
24+
return rob2;
25+
}
26+
}
27+
}
28+

0 commit comments

Comments
 (0)