最近,一直在科研与刷题之间周旋。正在研究第三篇论文,实验室同年级都已经出现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[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];
}