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。

相关推荐
hansang_IR2 天前
【题解】[COCI 2024/2025 #2] 流明 / Blistavost
c++·算法·动态规划·dp
2601_960906722 天前
下一代iPhone的迭代改进
决策树·随机森林·线性回归·动态规划
2501_942389553 天前
Epoch AI旗下FrontierMath的负责人Elliot Glazer
数据结构·决策树·动态规划·散列表
-森屿安年-4 天前
647. 回文子串
c++·算法·动态规划
啦啦啦啦啦zzzz4 天前
贪心算法和动态规划
c++·算法·贪心算法·动态规划
雪碧聊技术4 天前
力扣 72. 编辑距离——动态规划经典例题
算法·leetcode·动态规划
纳兰青华5 天前
回文侦探:三种境界破解最长回文子串
java·算法·动态规划
纳兰青华5 天前
拼图大师:从“暴力尝试“到“动态规划“的拆字艺术
java·算法·动态规划
星马梦缘5 天前
算法设计导论 课堂笔记
算法·动态规划·分治·时间复杂度·最优二叉树
城管不管6 天前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划