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 }
  • 相关阅读:
    FTP和SSH的区别
    Hadoop之回收站
    什么是簇?
    linux中环境变量的配置
    windows系统中的系统变量和用户变量,以及配置JDK中各个参数的意义
    linux 中yum和rpm 总结
    ajax请求之async:false/true的作用
    JavaScript eval() 函数的用法
    js模式
    数组的一些操作
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4822508.html
Copyright © 2011-2022 走看看