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。

相关推荐
木井巳1 天前
【动态规划: 路径问题】不同路径
java·算法·leetcode·动态规划
basketball6162 天前
动态规划第一章:引论
算法·动态规划·1024程序员节
木井巳2 天前
【动态规划: 线性dp】解码方法
java·算法·leetcode·动态规划·推荐算法
stolentime3 天前
SOS DP学习笔记
c++·笔记·学习·算法·贪心算法·动态规划·二进制
y1su4 天前
Leetcode 字符串模板
java·数据结构·算法·leetcode·职场和发展·动态规划
lvwangshu4 天前
P8981 「DROI」Round 1 距离 题解
动态规划·图论·题解·dp·树形dp·技巧·换根dp·性质题·思维好题
Tairitsu_H4 天前
[动态规划#1] 子数组 | 最大子数组和 | 环形子数组的最大和 | 乘积最大子数组 | 乘积为正数的最长子数组
算法·动态规划
罗湖老棍子4 天前
【例 2】牧场的安排(信息学奥赛一本通- P1593)三角形牧场(洛谷-P1284)
算法·动态规划·状压dp·状态压缩动态规划
Cccp.1234 天前
【leetcode】(十四)从暴力递归到动态规划
数据结构·算法·leetcode·动态规划