题解 | #打家劫舍(一)#
打家劫舍(一)
https://www.nowcoder.com/practice/c5fbf7325fbd4c0ea3d0c3ea6bc6cc79
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型
*/
public int rob (int[] nums) {
// write code here
if (nums.length==0) return 0;
if (nums.length==1) return nums[0];
if (nums.length==2) return Math.max(nums[0],nums[1]);
int[] f=new int[nums.length];
f[0]=nums[0];
f[1]= Math.max(nums[0],nums[1]);
for(int i=2;i<nums.length;i++)
{
f[i]=Math.max(f[i-1],f[i-2]+nums[i]);
}
return f[nums.length-1];
}
}
