LeetCode每日一题(1388. Pizza With 3n Slices)

There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows:

You will pick any pizza slice.
Your friend Alice will pick the next slice in the anti-clockwise direction of your pick.
Your friend Bob will pick the next slice in the clockwise direction of your pick.
Repeat until there are no more slices of pizzas.
Given an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick.

Example 1:

Input: slices = [1,2,3,4,5,6]
Output: 10

Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.

Example 2:

Input: slices = [8,9,8,6,1,1]
Output: 16

Explanation: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.

Constraints:

  • 3 * n == slices.length
  • 1 <= slices.length <= 500
  • 1 <= slices[i] <= 1000

有个评论提到这题本质跟 House Robber 系列中的某道题是一样的, 都是一个 circle array 中没法访问相同元素的问题。时间久了忘了了一干二净, 最后还是看别人的解析才回忆起来。

如果我们先忽略 circle array 的问题, 实际这题就是在一个 slice 中选出 slice.len() / 3 个不相邻的元素, 并且这些元素的加和值最大的问题。而加上 circle array 的条件之后, 不仅数组中相邻的两个元素成为互斥的, 数组的第一个和最后一个元素也成为互斥的,但是情况其实没有复杂多少,无非就是在原有的基础之上又分成了选择第一个元素和选择最后一个元素两种情况



use std::collections::HashMap;

impl Solution {
    fn dp(slices: &Vec<i32>, i: usize, j: usize, cache: &mut HashMap<(usize, usize), i32>) -> i32 {
        if j == 0 {
            return 0;
        }
        if i == 0 {
            return slices[0];
        }
        if i == 1 {
            return slices[0].max(slices[1]);
        }
        if let Some(c) = cache.get(&(i, j)) {
            return *c;
        }
        let pick = slices[i] + Solution::dp(slices, i - 2, j - 1, cache);
        let pass = Solution::dp(slices, i - 1, j, cache);
        let ans = pick.max(pass);
        cache.insert((i, j), ans);
        ans
    }
    pub fn max_size_slices(slices: Vec<i32>) -> i32 {
        let ignore_first = Solution::dp(
            &slices[1..].to_vec(),
            slices.len() - 2,
            slices.len() / 3,
            &mut HashMap::new(),
        );
        let ignore_last = Solution::dp(
            &slices[..slices.len() - 1].to_vec(),
            slices.len() - 2,
            slices.len() / 3,
            &mut HashMap::new(),
        );
        ignore_first.max(ignore_last)
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值