BM78- Robbery (1)

topic

You are an experienced thief. You are going to steal a row of rooms along the street. Each room has a certain amount of cash. In order to prevent being discovered, you cannot steal two adjacent rooms. You can't steal the second house; if you steal the second house, you can't steal the first house and the third house.

Given an integer array nums, the elements in the array represent the amount of cash stored in each room, please calculate the maximum amount stolen without being discovered.

Data range: The length of the array satisfies 1≤n≤2×10^5, and each value in the array satisfies 1≤num[i]≤5000.

Example 1

enter:

[1,2,3,4]

return value:

6

illustrate:

The optimal solution is to steal the 2nd and 4th rooms

Example 2

enter:

[1,3,6]

return value:

7

illustrate:

The optimal solution is to steal the first and third rooms

Example 3

enter:

[2,10,5]

return value:

10

illustrate:

The optimal solution is to steal the second room


the code

import java.util.*;

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param nums int整型一维数组
     * @return int整型
     */
    public int rob (int[] nums) {
        //1.创建dp表
        //dp[i]表示长度为i的数组,最多能偷取多少钱
        int[] dp = new int[nums.length + 1];

        //2.初始化
        //长度为1只能偷第一家
        dp[1] = nums[0];

        //3.填表
        for (int i = 2; i <= nums.length; i++) {
            //对于每家可以选择偷或者不偷
            dp[i] = Math.max(dp[i - 1], nums[i - 1] + dp[i - 2]);
        }

        //4.返回值
        return dp[nums.length];
    }
}

Guess you like

Origin blog.csdn.net/WWXDwrn/article/details/131623960