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。

相关推荐
leoufung8 小时前
LeetCode 221:Maximal Square 动态规划详解
算法·leetcode·动态规划
好易学·数据结构8 小时前
可视化图解算法77:零钱兑换(兑换零钱)
数据结构·算法·leetcode·动态规划·力扣·牛客网
Tisfy8 小时前
LeetCode 1458.两个子序列的最大点积:动态规划
算法·leetcode·动态规划·题解·dp
会员果汁1 天前
leetcode-动态规划-买卖股票
算法·leetcode·动态规划
leoufung2 天前
LeetCode动态规划经典题:Unique Paths 网格路径计数详解
算法·leetcode·动态规划
放荡不羁的野指针2 天前
leetcode150题-动态规划
算法·动态规划
水月wwww2 天前
【算法设计】动态规划
算法·动态规划
学海一叶3 天前
论文精读-《ReAct: Synergizing Reasoning and Acting in Language Models》,2022
论文阅读·人工智能·语言模型·动态规划·agent
leoufung4 天前
LeetCode 72. Edit Distance(编辑距离)动态规划详解
leetcode·动态规划·代理模式
无尽的罚坐人生4 天前
hot 100 42. 接雨水
数据结构·算法·leetcode·动态规划··双指针