当前位置:网站首页>2022.02.13 - SX10-30. Home raiding II

2022.02.13 - SX10-30. Home raiding II

2022-07-05 22:42:00 A CAI continues to work hard

1. subject

 Insert picture description here

2. Ideas

(1) Dynamic programming

  • Because the first and last one can only choose one to steal , Another family must not steal , therefore , You can delete the first or last one directly , This breaks the ring , Carry out dynamic planning respectively , Take the larger of the two times .

3. Code

public class Test {
    
    public static void main(String[] args) {
    
    }
}

class Solution {
    
    public int rob(int[] nums) {
    
        int n = nums.length;
        if (n == 1) {
    
            return nums[0];
        }
        if (n == 2) {
    
            return Math.max(nums[0], nums[1]);
        }
        int[] dp = new int[n];
        dp[0] = nums[0];
        dp[1] = Math.max(nums[0], nums[1]);
        for (int i = 2; i < n - 1; i++) {
    
            dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
        }
        int temp = dp[n - 2];
        dp[1] = nums[1];
        dp[2] = Math.max(nums[1], nums[2]);
        for (int i = 3; i < n; i++) {
    
            dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
        }
        return Math.max(temp, dp[n - 1]);
    }
}
原网站

版权声明
本文为[A CAI continues to work hard]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140407155301.html