题解 | #打家劫舍(一)#

打家劫舍(一)

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];
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务