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。

相关推荐
leoufung10 小时前
LeetCode动态规划经典题:Unique Paths 网格路径计数详解
算法·leetcode·动态规划
放荡不羁的野指针1 天前
leetcode150题-动态规划
算法·动态规划
水月wwww1 天前
【算法设计】动态规划
算法·动态规划
学海一叶2 天前
论文精读-《ReAct: Synergizing Reasoning and Acting in Language Models》,2022
论文阅读·人工智能·语言模型·动态规划·agent
leoufung2 天前
LeetCode 72. Edit Distance(编辑距离)动态规划详解
leetcode·动态规划·代理模式
无尽的罚坐人生2 天前
hot 100 42. 接雨水
数据结构·算法·leetcode·动态规划··双指针
小龙报3 天前
【算法通关指南:算法基础篇 】模拟算法专题:1. 铺地毯 2. 回文日期 3. 扫雷
c语言·数据结构·c++·算法·动态规划·知识图谱·visual studio
Dream it possible!3 天前
LeetCode 面试经典 150_Kadane_环形子数组的最大和(110_918_C++_中等)(动态规划)
c++·leetcode·面试·动态规划
少许极端3 天前
算法奇妙屋(二十二)-01背包问题(动态规划)
java·算法·动态规划·背包问题·01背包
leoufung3 天前
LeetCode 188. Best Time to Buy and Sell Stock IV - 三维DP详解
算法·leetcode·动态规划