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。

相关推荐
zephyr055 天前
DP 从放弃到拿捏:一份持续更新的动态规划题解清单(一)
算法·动态规划
mjhcsp5 天前
C++轮廓线 DP:从原理到实战的深度解析
开发语言·c++·动态规划
.格子衫.5 天前
031动态规划之数位DP——算法备赛
算法·动态规划
月挽清风5 天前
代码随想录第35天:动态规划
算法·动态规划
开开心心就好5 天前
安卓开源应用,超时提醒紧急人护独居安全
windows·决策树·计算机视觉·pdf·计算机外设·excel·动态规划
问好眼5 天前
《算法竞赛进阶指南》0x01 位运算-4.最短Hamilton路径
c++·算法·动态规划·位运算·信息学奥赛
不想看见4046 天前
Maximal Square 基本动态规划:二维--力扣101算法题解笔记
算法·leetcode·动态规划
Renhao-Wan6 天前
Java 算法实践(七):动态规划
java·算法·动态规划
Trouvaille ~6 天前
【动态规划篇】专题(二):路径问题——在网格图中的决策艺术
c++·算法·leetcode·青少年编程·动态规划