zoukankan      html  css  js  c++  java
  • 【LeetCode】213. House Robber II

    House Robber II

    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.

    Credits:
    Special thanks to @Freezen for adding this problem and creating all test cases.

    House Robber的差异在于,nums[0]和nums[n-1]不能同时包含,

    因此等同于nums[0...n-2]和nums[1...n-1]两者间取较大值。

    class Solution {
    public:
        int rob(vector<int>& nums) {
            if(nums.empty())
                return 0;
            if(nums.size() == 1)
                return nums[0];
            vector<int> nums1(nums);
            vector<int> nums2(nums);
            nums1.erase(nums1.begin());
            nums2.pop_back();
            return max(originRob(nums1), originRob(nums2));
        }
        int originRob(vector<int>& nums)
        {
            if(nums.empty())
                return 0;
            int prev2 = 0;
            int prev1 = nums[0];
            for(int i = 1; i < nums.size(); i ++)
            {
                int cur = max(prev2+nums[i], prev1);
                prev2 = prev1;
                prev1 = cur;
            }
            return prev1;
        }
    };

  • 相关阅读:
    OAF_OAF控件系列9
    OAF_OAF控件系列8
    OAF_OAF控件系列7
    OAF_OAF控件系列5
    OAF_OAF控件系列4
    OAF_OAF控件系列3
    OAF_OAF控件系列3
    OAF_OAF控件系列2
    OAF_OAF控件系列1
    PLSQL_性能优化索引Index介绍(概念)
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4619238.html
Copyright © 2011-2022 走看看