- Leetcode 3117. Minimum Sum of Values by Dividing Array
- 1. 解题思路
- 2. 代码实现
- 题目链接:3117. Minimum Sum of Values by Dividing Array
1. 解题思路
这一题思路上就是一个动态规划,我们只需要考察每一个元素是否需要放在当前的group当中还是作为新的group的开始元素,然后在所有的可能结果当中取最小值即可。
2. 代码实现
给出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.infif k >= m:return math.infif pre & nums[idx] < andValues[k]:return math.infelif 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。