Skip to content

Commit f249682

Browse files
committed
"House Robber II"
1 parent cf5dbd3 commit f249682

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
111111
| 216 | [Combination Sum III] | [C++](src/216.cpp) |
112112
| 215 | [Kth Largest Element in an Array] | [C](src/215.c) |
113113
| 214 | [Shortest Palindrome] | |
114-
| 213 | [House Robber II] | |
114+
| 213 | [House Robber II] | [C](src/213.c) |
115115
| 212 | [Word Search II] | [C](src/212.c) |
116116
| 211 | [Add and Search Word - Data structure design] | [C](src/211.c) |
117117
| 210 | [Course Schedule II] | |

src/213.c

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
#define max(a,b) ((a)>(b)?(a):(b))
5+
int robNoCircle(int num[], int n) {
6+
if (n == 0) return 0;
7+
int *dp = (int *)calloc(n + 2, sizeof(int));
8+
int i;
9+
dp[0] = dp[1] = 0; /* dummy */
10+
for (i = 2; i < n + 2; i++) {
11+
/* for each house, there are two choices: robbing and NOT robbing */
12+
if (dp[i - 2] + num[i - 2] > dp[i - 1]) { /* rob */
13+
dp[i] = dp[i - 2] + num[i - 2];
14+
}
15+
else { /* don't rob */
16+
dp[i] = dp[i - 1];
17+
}
18+
}
19+
int ans = dp[n + 1];
20+
free(dp);
21+
return ans;
22+
}
23+
24+
int rob(int* nums, int numsSize) {
25+
if (nums == NULL || numsSize == 0) return 0;
26+
if (numsSize == 1) return nums[0];
27+
return max(robNoCircle(nums, numsSize - 1), robNoCircle(nums + 1, numsSize - 1));
28+
}
29+
30+
int main() {
31+
int nums[] = { 1, 2, 3, 4, 5 };
32+
33+
assert(rob(nums, sizeof(nums) / sizeof(nums[0])) == 8);
34+
35+
printf("all tests passed!\n");
36+
37+
return 0;
38+
}

0 commit comments

Comments
 (0)