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。

相关推荐
长安er3 小时前
LeetCode 300/152/416/32 动态规划进阶题型总结(最长递增子序列→最长有效括号)
数据结构·算法·leetcode·动态规划·剪枝
好易学·数据结构4 小时前
可视化图解算法74:最小花费爬楼梯
数据结构·算法·leetcode·动态规划·力扣
少许极端8 小时前
算法奇妙屋(十九)-子序列问题(动态规划)
java·数据结构·算法·动态规划·子序列问题
长安er1 天前
LeetCode 01 背包 & 完全背包 题型总结
数据结构·算法·leetcode·动态规划·背包问题
阿恩.7701 天前
国际水电与电力能源期刊精选
经验分享·笔记·考研·动态规划·能源·制造
资深web全栈开发1 天前
LeetCode 3573. 买卖股票的最佳时机 V - 动态规划解法详解
算法·leetcode·动态规划
xu_yule1 天前
算法基础-动态规划
算法·动态规划
dyxal2 天前
动态规划:给“最优解”一张记住过去的备忘录
算法·动态规划·代理模式
长安er2 天前
LeetCode198打家劫舍:从回溯到动态规划的优化历程
算法·leetcode·动态规划·回溯·打家劫舍
scx201310042 天前
20251210 DP小测总结
c++·动态规划