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

    Question

    You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

    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 1 -- DP

    The key is to find the relation dp[i] = Math.max(dp[i-1], dp[i-2]+num[i-1]). Time complexity O(n), space cost O(n).

     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;
     6         int[] dp = new int[length + 1];
     7         dp[0] = 0;
     8         dp[1] = nums[0];
     9         for (int i = 2; i <= length; i++) {
    10             dp[i] = Math.max(dp[i - 1], nums[i - 1] + dp[i - 2]);
    11         }
    12         return dp[length];
    13     }
    14 }

    Solution 2

    Another method is to use two counters, one for even number and the other for odd number.

     1 public class Solution {
     2     public int rob(int[] nums) {
     3         if (nums == null || nums.length < 1)
     4             return 0;
     5         int odd = 0, even = 0, length = nums.length;
     6         for (int i = 0; i < length; i++) {
     7             if (i % 2 == 0) {
     8                 even += nums[i];
     9                 even = even > odd ? even : odd;
    10             } else {
    11                 odd += nums[i];
    12                 odd = odd > even ? odd : even;
    13             }
    14         }
    15         return even > odd ? even : odd;
    16     }
    17 }
  • 相关阅读:
    vue项目中兼容ie8以上浏览器的配置
    vue项目中event bus的简单使用
    js中的正则表达式小结1
    sourceTree跳过注册
    日期时间格式化
    阿里矢量图标库的使用
    mySql 常用命令
    php 常用的系统函数
    php mySql常用的函数
    php 关于php创建 json文件 和 对文件增删改查 示例
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4822508.html
Copyright © 2011-2022 走看看