|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <string.h> |
| 4 | + |
| 5 | +static inline int max(int a, int b) |
| 6 | +{ |
| 7 | + return a > b ? a : b; |
| 8 | +} |
| 9 | + |
| 10 | +static int _rob(int* nums, int numsSize) |
| 11 | +{ |
| 12 | + int i; |
| 13 | + int **money = malloc((numsSize + 1) * sizeof(int *)); |
| 14 | + for (i = 0; i < numsSize + 1; i++) { |
| 15 | + money[i] = malloc(2 * sizeof(int)); |
| 16 | + memset(money[i], 0, 2 * sizeof(int)); |
| 17 | + } |
| 18 | + |
| 19 | + for (i = 1; i <= numsSize; i++) { |
| 20 | + int cash = nums[i - 1]; |
| 21 | + money[i][0] = max(money[i - 1][0], money[i - 1][1]); |
| 22 | + money[i][1] = money[i - 1][0] + cash; |
| 23 | + } |
| 24 | + |
| 25 | + return max(money[numsSize][0], money[numsSize][1]); |
| 26 | +} |
| 27 | + |
| 28 | +static int rob(int* nums, int numsSize) |
| 29 | +{ |
| 30 | + if (numsSize == 0) { |
| 31 | + return 0; |
| 32 | + } else if (numsSize == 1) { |
| 33 | + return nums[0]; |
| 34 | + } else { |
| 35 | + return max(_rob(nums + 1, numsSize - 1), _rob(nums, numsSize - 1)); |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +int main(int argc, char **argv) |
| 40 | +{ |
| 41 | + int i, count = argc - 1; |
| 42 | + int *nums = malloc(count * sizeof(int)); |
| 43 | + for (i = 0; i < count; i++) { |
| 44 | + nums[i] = atoi(argv[i + 1]); |
| 45 | + } |
| 46 | + printf("%d\n", rob(nums, count)); |
| 47 | + return 0; |
| 48 | +} |
0 commit comments