Leetcode 3117. Minimum Sum of Values by Dividing Array

  • [Leetcode 3117. Minimum Sum of Values by Dividing Array](#Leetcode 3117. Minimum Sum of Values by Dividing Array)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题思路上就是一个动态规划,我们只需要考察每一个元素是否需要放在当前的group当中还是作为新的group的开始元素,然后在所有的可能结果当中取最小值即可。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def minimumValueSum(self, nums: List[int], andValues: List[int]) -> int:
        n, m = len(nums), len(andValues)

        @lru_cache(None)
        def dp(idx, k, pre):
            if idx >= n:
                return 0 if k >= m else math.inf
            if k >= m:
                return math.inf
            if pre & nums[idx] < andValues[k]:
                return math.inf
            elif pre & nums[idx] == andValues[k]:
                return min(nums[idx] + dp(idx+1, k+1, nums[idx+1] if idx+1 < n else -1), dp(idx+1, k, pre & nums[idx]))
            else:
                return dp(idx+1, k, pre & nums[idx])
        
        ans = dp(0, 0, nums[0])
        return ans if ans != math.inf else -1

提交代码评测得到:耗时1353ms,占用内存414.1MB。

相关推荐
如何原谅奋力过但无声2 小时前
【灵神高频面试题合集21-25】动态规划(下)
算法·动态规划
lvwangshu3 小时前
CF813D Two Melodies 题解
动态规划·题解·技巧·性质题·思维好题
longlongzihan14 小时前
从LeetCode 70. 爬楼梯看动态规划:如何精准推导状态转移方程?
c++·算法·leetcode·动态规划
Rnan-prince19 小时前
LeetCode 股票买卖系列:一个动态规划状态机模板通吃四题
leetcode·动态规划
随意起个昵称2 天前
【背包dp】输出方案路径
c++·动态规划
青山木2 天前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
随意起个昵称2 天前
【分组背包】洛谷刷题合集
算法·动态规划
随意起个昵称2 天前
【线性DP】P10156 [LSOT-2] 胜者组
c++·动态规划
Zootopia6263 天前
多架 eVTOL集群排班调度方案思考
人工智能·算法·数学建模·matlab·动态规划·无人机·evtol
随意起个昵称3 天前
【单调队列优化DP】U301134 绿色通道
算法·动态规划