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.
public class Solution {
public int rob(int[] nums) {
if(nums.length<1) return 0;
int maxSoFar=nums[0];
int lastIndex=0;
int lastMax=0;
//33,1,2,3
for(int i=1; i<nums.length; i++){
if(i-lastIndex==1)
{
int temp=lastMax+nums[i];
if(temp>maxSoFar){
lastMax=maxSoFar;
maxSoFar=temp;
lastIndex=i;
}else
lastMax=temp;
}
else{
lastMax=maxSoFar;
lastIndex=i;
maxSoFar+=nums[i];
}
}
return maxSoFar;
}
}Dynamic Programming
本文介绍了一种使用动态规划解决的专业窃贼问题:如何在不触动相邻房屋警报的情况下,从一排房屋中窃取最大金额。通过具体算法实现,展示了如何计算并返回在这些限制条件下可窃取的最大金额。
885

被折叠的 条评论
为什么被折叠?



