美文网首页
198. House Robber

198. House Robber

作者: YellowLayne | 来源:发表于2017-06-26 11:29 被阅读0次

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

      本文链接:https://www.haomeiwen.com/subject/rnwdcxtx.html