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.

    Credits:
    Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

    
    

    1
    public class Solution 2 { 3 public static int rob(int[] num) 4 { 5 int a=0; 6 int b=0; 7 for(int i=0;i<num.length;i++) 8 { 9 if(i%2==0) 10 a=Math.max(a+num[i],b); 11 else 12 b=Math.max(a,b+num[i]); 13 } 14 return Math.max(a, b); 15 } 16 public static void main(String args[]) 17 { 18 // System.out.println("---"); 19 int[]num={226,174,214,16,218,48,153,131,128,17,157,142}; 20 int sum=rob(num); 21 System.out.println(sum); 22 } 23 }

     1  public int rob(int[] num) {
     2         int n = num.length;
     3         if (n < 2)
     4             return n == 0 ? 0 : num[0];
     5         int[] cache = new int[n];
     6         cache[0] = num[0];
     7         cache[1] = num[0] > num[1] ? num[0] : num[1];
     8         for (int i = 2; i < n; i++) {
     9             cache[i] = cache[i - 2] + num[i];
    10             cache[i] = cache[i] > cache[i-1]? cache[i] : cache[i-1];
    11         }
    12         return cache[n - 1];
    13     }
  • 相关阅读:
    C#中的async和await
    Windows 10 error code 0x80072efd
    Winform中调用js函数
    Windows 10 x64 安装 Visual Basic 6.0 SP6
    用谷歌浏览器来当手机模拟器
    Windows 10 解决 0x80070021 错误
    正则匹配所有中英文标点
    本地网站部署注意细节
    电信光猫 路由+拨号混合设置 备忘
    Restful 支持 自定义序列化
  • 原文地址:https://www.cnblogs.com/qq1029579233/p/4401704.html
Copyright © 2011-2022 走看看