面试题 17.16. The Masseuse LCCI(Leetcode每日一题-2020.03.24)

Problem

A popular masseuse receives a sequence of back-to-back appointment requests and is debating which ones to accept. She needs a break between appointments and therefore she cannot accept any adjacent requests. Given a sequence of back-to-back appoint­ ment requests, find the optimal (highest total booked minutes) set the masseuse can honor. Return the number of minutes.

Note: This problem is slightly different from the original one in the book.

Example1

Input: [1,2,3,1]
Output: 4
Explanation: Accept request 1 and 3, total minutes = 1 + 3 = 4

Example2

Input: [2,7,9,3,1]
Output: 12
Explanation: Accept request 1, 3 and 5, total minutes = 2 + 9 + 1 = 12

Example3

Input: [2,1,4,5,3,1,1,3]
Output: 12
Explanation: Accept request 1, 3, 5 and 8, total minutes = 2 + 4 + 3 + 3 = 12

Solution

Solution1

dp[i]表示到nums[i]时,的最大时间。

dp[i]有在以下两种情况中选择大的一个,

  • dp[i-2] + nums[i],accept nums[i]
  • dp[i-2],reject nums[i]
class Solution {
public:
    int massage(vector<int>& nums) {
        if(nums.empty())
            return 0;
        if(nums.size() == 1)
            return nums[0];

        vector<int> dp(nums.size(),0);

        dp[0] = nums[0];
        dp[1] = max(nums[0],nums[1]);
        

        for(int i = 2;i<nums.size();++i)
        {
           dp[i] = max(dp[i-1],dp[i-2] + nums[i]);
        }

        return dp[nums.size()-1];

    }
};

Solution2

从上面的方法可以看到,dp[i]只与dp[i-1]及dp[i-2]和nums[i]相关,所以,没有必要维护整个dp数组。

class Solution {
public:
    int massage(vector<int>& nums) {
        if(nums.empty())
            return 0;
        if(nums.size() == 1)
        {
            return nums[0];
        }

        if(nums.size() == 2)
            return max(nums[0],nums[1]);

        int minus2 = nums[0];
        int minus1 = max(nums[0],nums[1]);
        int cur = 0;
        for(int i = 2;i<nums.size();++i)
        {
            cur = max(minus1,minus2 + nums[i]);
            minus2 = minus1;
            minus1 = cur;
        }

        return cur;

    }
};

Related problem

198.House Robber

发布了526 篇原创文章 · 获赞 215 · 访问量 54万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/105084075
今日推荐