leetcode之旅-easy(House Robber)

最近,一直在科研与刷题之间周旋。正在研究第三篇论文,实验室同年级都已经出现RANK A 的档次了,压力山大!对于不读博的我来说,还是抓紧刷题比较实在。

leetcode还没有做多少,但是我希望这个能够成为激励我不断加速的动力。

对于算法已经放下很久的同学,我想说:不要灰心,从easy开始刷起,不断增加信心。(PS:我一直认为心理战术远比技术重要的多大笑,做一个内心强大的程序媛)


进入正题,看招:

House Robber

 

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.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

简单DP,为每个房间记录一个当前最大财富值dp[n],对于dp[i]来说,可以由两种情况获得:(1)从前一个间隔房间财富值加上第i个房间的财富值。(2)上一个房间的财富值;

两者取最大即可由局部最大得到全局最大,即DP[n]为所求。

int maxx(int a,int b)
{
    return a>b ? a:b;
}
int rob(int num[], int n)

 {
   int dp[n];
    int i = 0;
    dp[0] = num[0];
    dp[1] = maxx(num[0],num[1]);
    for(i= 2;i<n;i++)
   {
        dp[i] = maxx(dp[i-2]+num[i],dp[i-1]);
    }
   return dp[n-1];
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值