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。

相关推荐
安於宿命38 分钟前
0/1背包问题总结
c语言·c++·算法·leetcode·动态规划
titan TV man1 小时前
上海市计算机学会竞赛平台2024年6月月赛丙组超级奇数
算法·数学建模·动态规划
Espresso Macchiato3 小时前
Leetcode 3213. Construct String with Minimum Cost
动态规划·leetcode hard·trie树·leetcode 3213·leetcode周赛405
观鉴词recommend3 小时前
【c++刷题笔记-动态规划】day32: 509. 斐波那契数 、 70. 爬楼梯 、 746. 使用最小花费爬楼梯
c++·笔记·算法·leetcode·动态规划
Scouser_H1 天前
二刷算法训练营Day53 | 动态规划(14/17)
算法·动态规划
天下烛火空明2 天前
【代码随想录算法训练营第37期 第三十八天 | LeetCode509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯】
算法·动态规划
安於宿命2 天前
DP:完全背包问题
c语言·c++·算法·leetcode·动态规划
c沫栀2 天前
C. Boring Day(cf955)
c语言·c++·算法·动态规划
EQUINOX12 天前
换根dp,CF 633F - The Chocolate Spree
算法·动态规划