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

打家劫舍(一)

http://www.nowcoder.com/practice/c5fbf7325fbd4c0ea3d0c3ea6bc6cc79

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param nums int整型一维数组 
     * @return int整型
     */
    // 20 1 1 20
    // 20 1 1 1 20
    public int rob (int[] nums) {
        // write code here
        int N = nums.length;
        if(N == 1) {
            return nums[0];
        } else if(N == 2) {
            return Math.max(nums[0], nums[1]);
        }
        int[] dp = new int[N];
        dp[0] = nums[0];
        dp[1] = nums[1];
        dp[2] = nums[0] + nums[2];
        for(int i = 3; i < N; i++) {
            dp[i] = Math.max(dp[i - 2], dp[i - 3]) + nums[i];
        }
        return Math.max(dp[N - 1], dp[N - 2]);
    }
}
全部评论

相关推荐

07-10 14:08
已编辑
江西农业大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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