刷题-力扣-面试题 17.16. 按摩师

面试题 17.16. 按摩师

题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/the-masseuse-lcci/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目描述

一个有名的按摩师会收到源源不断的预约请求,每个预约都可以选择接或不接。在每次预约服务之间要有休息时间,因此她不能接受相邻的预约。给定一个预约请求序列,替按摩师找到最优的预约集合(总预约时间最长),返回总的分钟数。

注意:本题相对原题稍作改动

示例 1:

输入: [1,2,3,1]
输出: 4
解释: 选择 1 号预约和 3 号预约,总时长 = 1 + 3 = 4。

示例 2:

输入: [2,7,9,3,1]
输出: 12
解释: 选择 1 号预约、 3 号预约和 5 号预约,总时长 = 2 + 9 + 1 = 12。

示例 3:

输入: [2,1,4,5,3,1,1,3]
输出: 12
解释: 选择 1 号预约、 3 号预约、 5 号预约和 8 号预约,总时长 = 2 + 4 + 3 + 3 = 12。

题目分析

  1. 根据题目描述计算最大的不连续序列的和
  2. 假设f(x)表示前x位最大不连续序列的和,有f(x)=max(f(x-1),f(x-2)+nums[x])

代码

class Solution {
public:
    int massage(vector<int>& nums) {
        int front = 0;
        int rear = 0;
        for (auto it = nums.cbegin(); it != nums.cend(); ++it) {
            int tmp = max(front + *it, rear);
            front = rear;
            rear = tmp;
        }
        return rear;
    }
};
原文地址:https://www.cnblogs.com/HanYG/p/14748730.html