📅  最后修改于: 2023-12-03 15:22:08.011000             🧑  作者: Mango
问题描述: 给定一个数组,从中移除尽可能少的数,使得剩余数的总和模M等于X。
def min_remove_to_make_mod_sum_equal(array, X, M):
n = len(array)
dp = [[0 for j in range(M)] for i in range(n+1)]
for i in range(n+1):
dp[i][0] = 1
for i in range(1, n+1):
mod = array[i-1] % M
for j in range(M):
dp[i][j] = dp[i-1][j]
if j >= mod:
dp[i][j] += dp[i-1][j-mod]
return -1 if dp[n][X] == 0 else n - dp[n][X]
array = [2,3,6,7,9]
X = 7
M = 5
print(min_remove_to_make_mod_sum_equal(array, X, M))
该算法的时间复杂度为O(nM),空间复杂度为O(nM)。