zoukankan      html  css  js  c++  java
  • Leetcode 213. House Robber II

    213. House Robber II

    • Total Accepted: 33705
    • Total Submissions: 106420
    • Difficulty: Medium

    Note: This is an extension of House Robber.

    After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

    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.

    思路:基本想法和Leetcode 198. House Robber类似,就是形成了环。不过可以这么考虑:在房间数>=2时,盗窃第0间或者不盗窃第0间,取2种情况的较大值。

    代码:

     1 class Solution {
     2 public:
     3     int rob(int low,int high,vector<int> nums){
     4         int pre=0,cur=0,i;
     5         for(i=low;i<=high;i++){
     6             cur=max(cur+nums[i],pre);
     7             swap(cur,pre);
     8         }
     9         return pre;
    10     }
    11     int rob(vector<int>& nums) {
    12         int n=nums.size();
    13         if(n<2) return n?nums[0]:0;
    14         return max(rob(0,n-2,nums),rob(1,n-1,nums));
    15     }
    16 };
  • 相关阅读:
    装饰者模式
    Linux top命令
    Java基础--单例类创建和测试
    Mybatis动态sql
    bmp图片格式及读取
    自然语言处理--nltk安装及wordnet使用详解
    Spring注解
    struts2 + spring + mybatis 框架整合
    Java基础--ThreadLocal
    Java基础--压缩和解压缩gz包
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5708562.html
Copyright © 2011-2022 走看看