zoukankan      html  css  js  c++  java
  • House Robber

    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.

    Example

    Given [3, 8, 4], return 8.

    一开始用了一个一位数组做DP, 后来看了提示用两个变量即可,降低了空间复杂度

     1 public class Solution {
     2     /**
     3      * @param A: An array of non-negative integers.
     4      * return: The maximum amount of money you can rob tonight
     5      */
     6     public long houseRobber(int[] A) {
     7         // write your code here
     8         if(A==null||A.length==0) return 0;
     9         
    10         long f1 = 0;
    11         long f2 = 0;
    12         
    13         for(int i=1;i<=A.length;i++){
    14             long temp1=f1;
    15             f1 = Math.max(f1, f2+A[i-1]);
    16             f2=temp1;
    17         }
    18         return f1;
    19     }
    20 }
  • 相关阅读:
    Redis涉及的概念
    Redis高级教程
    Redis基础入门
    Java多线程面试题
    Java集合面试题
    Java集合基础
    Java基础面试题总结
    Zookeeper Basics
    GitLab基础入门
    阿里云ECS服务器Docker安装Tomcat过程记录
  • 原文地址:https://www.cnblogs.com/xinqiwm2010/p/6835414.html
Copyright © 2011-2022 走看看