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。

相关推荐
晒太羊的猫10 小时前
hot100动态规划刷题
算法·动态规划
Logic10114 小时前
C语言/数据结构动态规划题解:爬楼梯(含坏台阶)——避开障碍物的路径计数
c语言·数据结构·动态规划·时间复杂度·空间复杂度·算法题·爬楼梯
如何原谅奋力过但无声20 小时前
【灵神高频面试题合集21-25】动态规划(下)
算法·动态规划
lvwangshu21 小时前
CF813D Two Melodies 题解
动态规划·题解·技巧·性质题·思维好题
longlongzihan1 天前
从LeetCode 70. 爬楼梯看动态规划:如何精准推导状态转移方程?
c++·算法·leetcode·动态规划
Rnan-prince2 天前
LeetCode 股票买卖系列:一个动态规划状态机模板通吃四题
leetcode·动态规划
随意起个昵称2 天前
【背包dp】输出方案路径
c++·动态规划
青山木2 天前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
随意起个昵称3 天前
【分组背包】洛谷刷题合集
算法·动态规划
随意起个昵称3 天前
【线性DP】P10156 [LSOT-2] 胜者组
c++·动态规划