首页 > 其他分享 >LeetCode刷题(75)~按摩师

LeetCode刷题(75)~按摩师

时间:2023-01-12 14:38:02浏览次数:35  
标签:return nums 预约 len LeetCode int 75 按摩师 pre2


题目描述

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

示例 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。

解答 By 海轰

提交代码(动态规划)

int massage(vector<int>& nums) {
int len=nums.size();
if(len==0) return 0;
if(len==1) return nums[0];
if(len==2) return max(nums[0],nums[1]);
int pre1=nums[0];
int pre2=max(nums[0],nums[1]);
int resmax=pre2;
for(int i=2;i<len;++i)
{
resmax=max(nums[i]+pre1,pre2);
pre1=pre2;
pre2=resmax;
}
return pre2;
}

运行结果

LeetCode刷题(75)~按摩师_提交代码

题目来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/the-masseuse-lcci


标签:return,nums,预约,len,LeetCode,int,75,按摩师,pre2
From: https://blog.51cto.com/u_15939722/6004155

相关文章