BM79- Robbery (2)

topic

You are an experienced thief. You are going to steal a row of rooms along the lake. Each room has a certain amount of cash. In order to prevent being discovered, you cannot steal two adjacent rooms. That is, if you steal the first room, You can't steal the second house. If you steal the second house, you can't steal the first and third houses. The rooms along the lake form a closed circle, that is, the first room and the last room are considered adjacent.

Given an integer array nums of length n, 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≤nums[i]≤5000.

Example 1

enter:

[1,2,3,4]

return value:

6

illustrate:

The optimal solution is to steal the 24th room

Example 2

enter:

[1,3,6]

return value:

6

illustrate:

Since 1 and 3 are adjacent, the optimal solution is to steal the third room


the code

import java.util.*;

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param nums int整型一维数组
     * @return int整型
     */
    public int rob (int[] nums) {
        int n = nums.length;
        return Math.max(nums[0] + rob1(nums, 2, n - 2), rob1(nums, 1, n - 1));
    }

    //打家劫舍1
    public int rob1(int[] nums, int left, int right) {
        //边界条件处理
        if (left > right) {
            return 0;
        }

        //1.创建dp表
        int n = nums.length;
        int[] f = new int[n];
        int[] g = new int[n];

        //2.初始化
        f[left] = nums[left];

        //3.填表
        for (int i = left + 1; i <= right; i++) {
            f[i] = g[i - 1] + nums[i];
            g[i] = Math.max(g[i - 1], f[i - 1]);
        }

        //4.返回值
        return Math.max(f[right], g[right]);
    }
}

Guess you like

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