zoukankan      html  css  js  c++  java
  • House Robber II 解答

    Question

    After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

    Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

    Solution

    Key to this problem is to break the circle. So we can consider two situations here:

    1. Not include last element

    2. Not include first element

    Therefore, we can use the similar dynamic programming approach to scan the array twice and get the larger value.

     1 public class Solution {
     2     public int rob(int[] nums) {
     3         if (nums == null || nums.length < 1)
     4             return 0;
     5         int length = nums.length, tmp1, tmp2;
     6         if (length == 1)
     7             return nums[0];
     8         int[] dp = new int[length];
     9         dp[0] = 0;
    10         dp[1] = nums[0];
    11         // First condition: include first element, not include last element;
    12         for (int i = 2; i < length; i++)
    13             dp[i] = Math.max(dp[i - 1], nums[i - 1] + dp[i - 2]);
    14         tmp1 = dp[length - 1];
    15         // Second condition: include last element, not include first element;
    16         dp = new int[length];
    17         dp[0] = 0;
    18         dp[1] = nums[1];
    19         for (int i = 2; i < length; i++)
    20             dp[i] = Math.max(dp[i - 1], nums[i] + dp[i - 2]);
    21         tmp2 = dp[length - 1];
    22         return tmp1 > tmp2 ? tmp1 : tmp2;
    23     }
    24 }
  • 相关阅读:
    奖学金 题解
    大数加法
    删除倒数第 N 个节点
    css中行内元素默认间隙解决方案
    vuecli3项目中优化lodash/moment使用
    谷歌浏览器input输入框自动填充数据
    vuecli3首页白屏优化
    highcharts开发交易所的行情走势图
    react-native使用flatlist上拉加载下拉刷新
    放大预览图片不失真
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4822577.html
Copyright © 2011-2022 走看看