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     }
  • 相关阅读:
    DEVMODE 结构体
    VS2019如何将主菜单从标题栏移到单独一行
    最近学到的东西
    线上问题处理相关思考
    mybatis+spring
    jenkins
    自动化case校验点
    Sqlserver大数据迁移,导出-》导入(BULK INSERT)
    阿里P7大佬带你解密Sentinel
    《高可用系列》-限流神器Sentinel,不了解一下吗?
  • 原文地址:https://www.cnblogs.com/qq1029579233/p/4401704.html
Copyright © 2011-2022 走看看