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。

相关推荐
样例过了就是过了17 小时前
LeetCode热题100 爬楼梯
c++·算法·leetcode·动态规划
样例过了就是过了21 小时前
LeetCode热题100 跳跃游戏
c++·算法·leetcode·贪心算法·动态规划
做怪小疯子21 小时前
LeetCode刷题——15.动态规划模式
算法·leetcode·动态规划
WolfGang0073211 天前
代码随想录算法训练营 Day29 | 动态规划 part02
算法·动态规划
样例过了就是过了1 天前
LeetCode热题100 跳跃游戏 II
c++·算法·leetcode·贪心算法·动态规划
故事和你911 天前
洛谷-算法1-2-排序2
开发语言·数据结构·c++·算法·动态规划·图论
花月C2 天前
线性动态规划(Linear DP)
算法·动态规划·代理模式
WolfGang0073212 天前
代码随想录算法训练营 Day28 | 动态规划 part01
算法·动态规划
散峰而望2 天前
【基础算法】动态规划从入门到进阶:记忆化搜索、线性 DP、LIS/LCS 一网打尽
c++·后端·算法·github·深度优先·动态规划·代理模式
xiaoye-duck2 天前
《算法题讲解指南:动态规划算法--子序列问题(附总结)》--32.最长的斐波那契子序列的长度,33.最长等差数列,34.等差数列划分II-子序列
c++·算法·动态规划