[每日一题] 按摩师

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

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

思路:

f(n) 数组长度为 n 时,返回此时最长的分钟数

可能性分析:

  • 选择下标为 n 的顾客(下标为 n - 1 的顾客比不选),res1 = f(n-2) + num[ n ]
  • 不选择下标为 n 的顾客(为了时间最长,n - 1 号顾客必选)res2 = f ( n-1)
  • 决策:res = max( res1 , res2 )

解法一:暴力递归

def massage2(nums):
    return process(nums, len(nums) - 1)


def process(nums, index):
    if index < 0: return 0
    if index == 0: return nums[0]
    if index == 1: return max(nums[0], nums[1])

    return max(nums[index] + process(nums, index - 2), process(nums, index - 1))

解法二:动态规划

动态规划的模式:从左向右尝试

递归公式: f ( n ) = m a x ( f ( n − 2 ) + n u m [ n ] , f ( n − 1 ) ) f(n)=max( f(n-2)+num[n],f(n-1) ) f(n)=max(f(n2)+num[n],f(n1))

代码:

def massage(nums):
    if not nums: return 0
    s1 = nums[0]
    s2 = max(nums[:2])
    res = max(s1, s2)
    for i in range(2, len(nums)):
        res = max(s1 + nums[i], s2)
        s1 = s2
        s2 = res

    return res

print(massage([1, 2, 3, 1]))
print(massage([2, 7, 9, 3, 1]))
print(massage([2, 1, 4, 5, 3, 1, 1, 3]))
print(massage([2,1,1,2]))

对数器

import random

def generator_random_array(max_value, max_size):
    return [int(random.random() * max_value) + 1 for _ in range(int(random.random() * max_size))]

def check():
    max_value = 20
    max_size = 20
    for i in range(50):
        arr = generator_random_array(max_value, max_size)
        res1 = massage(arr)
        res2 = massage2(arr)
        if res1 != res2:
            print("ERROR", res1, res2, arr)
    print("OVER!")

check()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值