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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容