按摩师 - 简单

*************

C++

topic: 面试题 17.16. 按摩师 - 力扣(LeetCode)

*************

Inspect the topic first.

And It just remainds me another topic, which is stocks problems.

买卖股票的最佳时机 - 合集-优快云博客https://blog.youkuaiyun.com/ElseWhereR/article/details/144608599?spm=1001.2014.3001.5501

By the way, do you know the king of massage?

Topic like this is to define the states of the each day. In the day i, receive the appointment or reject the appointment. Define dp[i] is the maxmum work time. 

for the i appointment, two choices, receive or reject.

  1. accepts the i-th appointment, but then she can't accept the i-1th appointment, because the total time is dp[i-2] + nums[i].
  2. doesn't accept the i-th appointment, then the total time is dp[i-1].

So the transfer equation is 

dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]).

int dp[0] = nums[1];

int dp[1] = max(nums[1], nums[2])

for ecample:

Suppose `nums = [1, 2, 3, 4, 5]`.

- `n = 5`

- `dp[0] = 1`

- `dp[1] = max(1, 2) = 2`

- `dp[2] = max(2, 1 + 3) = max(2, 4) = 4`

- `dp[3] = max(4, 2 + 4) = max(4, 6) = 6`

- `dp[4] = max(6, 4 + 5) = max(6, 9) = 9`

So the maximum profit is 9, which seems correct. She can take appointments 1 (1), 3 (3), and 5 (5), totaling 9.

class Solution {
public:
    int massage(vector<int>& nums) {

        // always initilize something here
        int n = nums.size();

        vector<int> dp(n, 0);
        dp[0] = nums[1];
        dp[1] = max(nums[1], nums[2]);
        
        for (int i = 2; i < n; i++){
            dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]);
        }
        
        return dp[n];
    }
};

The code looks beautiful and runs error.

I forget about the boundary conditions. 

if n = 0; return 0;

if n = 1; return nums[0];

class Solution {
public:
    int massage(vector<int>& nums) {
        int n = nums.size();
        if (n == 0) return 0;
        if (n == 1) return nums[0];
        
        vector<int> dp(n, 0);
        dp[0] = nums[0];
        dp[1] = max(nums[0], nums[1]);
        
        for (int i = 2; i < n; i++) {
            dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]);
        }
        
        return dp[n - 1];
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值