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

    You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, 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 1:

    Input: [2,3,2]
    Output: 3
    Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
                 because they are adjacent houses.
    

    Example 2:

    Input: [1,2,3,1]
    Output: 4
    Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
                 Total amount you can rob = 1 + 3 = 4.

    题目大意:房子以圆形布置,小偷同时偷相邻的房屋就会报警。求在不报警的前提下,能偷到的最多钱数。

    分析:由于圆形,第0家和第n家(最后一家)不能同时被偷,因此分两种情况转化为房子呈直线布置的情况就好了(0, ..., n - 1)和(1, ..., n)

     1 class Solution {
     2 public:
     3     int rob(vector<int>& nums) {
     4         int len = nums.size();
     5         if (len == 0)
     6             return 0;
     7         if (len == 1)
     8             return nums[0];
     9         return max(robOriginal(nums, 0, len - 2, len), robOriginal(nums, 1, len - 1, len));
    10     }
    11 private:
    12     int robOriginal(vector<int> nums, int l, int r, int len) {
    13         int prev = 0, cur = 0;
    14         for (int i = l; i <= r; i++) {
    15             int temp = max(cur, prev + nums[i]);
    16             prev = cur;
    17             cur = temp;
    18         }
    19         return cur;
    20     }
    21 };
  • 相关阅读:
    反射+自定义注解,实现获取注解标记的属性
    jeecg导出Excel
    Date类的getYear(),getMonth过时,现在的获取方法
    Mysql的sql语句,Delete 中包含 not in
    EhCache与Redis的比较
    SpringMVC+Bootstrap项目
    按位运算| ^
    按步长检索数据,放缓有问题数据的处理
    DateTime 格式相比较,timestampdiff() 函数的运用
    作用域在函数定义时就已经确定了。而不是在函数调用时确定
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11467090.html
Copyright © 2011-2022 走看看