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。

相关推荐
GG不是gg4 小时前
动态规划进阶:转移方程优化技巧全解
动态规划
范特西_10 小时前
不同的子序列-二维动态规划
算法·动态规划
花开富贵ii11 小时前
代码随想录算法训练营第三十八天、三十九天|动态规划part11、12
java·数据结构·算法·leetcode·动态规划
发发发发8881 天前
leetcode 674.最长连续递增序列
java·数据结构·算法·leetcode·动态规划·最长连续递增序列
是店小二呀2 天前
【动态规划 | 01背包】动态规划经典:01背包问题详解
算法·动态规划
shenghaide_jiahu4 天前
数学建模——递归和动态规划
算法·数学建模·动态规划
凯子坚持 c4 天前
动态规划专题:详解二维费用背包问题——以“一和零”与“盈利计划”为例
算法·动态规划
是店小二呀4 天前
【动态规划 | 子序列问题】子序列问题的最优解:动态规划方法详解
算法·动态规划·代理模式
屈臣6 天前
AtCoder Beginner Contest 417 (A-E题解)
动态规划·dfs·二分
Morriser莫6 天前
动态规划Day7学习心得
算法·动态规划