• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

xxxqqq

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

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 }

 

posted on 2017-05-10 13:08  xxxqqq  阅读(253)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3