198. House Robber

1.描述

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that 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.

2.分析

动态规划

3.代码

int rob(int* nums, int numsSize) {
    if (NULL == nums || numsSize <= 0) return 0;
    
    int* dp_take = (int*)malloc(sizeof(int) * numsSize);
    int* dp_ignore = (int*)malloc(sizeof(int) * numsSize);
    dp_take[0] = nums[0];
    dp_ignore[0] = 0;
    for (unsigned int i = 1; i < numsSize; ++i) {
        dp_take[i] = dp_ignore[i-1] + nums[i];
        dp_ignore[i] = dp_take[i-1] > dp_ignore[i-1] ? dp_take[i-1] : dp_ignore[i-1];
    }
    int result = dp_take[numsSize-1] > dp_ignore[numsSize-1] ? dp_take[numsSize-1] : dp_ignore[numsSize-1];
    free(dp_take);
    dp_take = NULL;
    free(dp_ignore);
    dp_ignore = NULL;
    return result;
}

你可能感兴趣的:(198. House Robber)