Given an array A, you can repeatedly delete any contiguous subarrays with length k that sum to tar from it. Output whether A can be made empty through this process.
A is an integer array, k is a positive integer, tar is an integer.
For example, A=[1,2,3,4];k=2;tar=5
Then you can delete [2,3] from A so that it becomes [1,4]. Then you delete [1,4] from A; it becomes empty. Therefore, the algorithm should output True.
Currently I have found a O(n^2/k*comb(n/k,k)) algorithm. Is there a better one?
My algorithm
Firstly, use dp, find whether A[i:j] can be empty, then enumerate all elements of the last deleted subarray, in time O(comb((j-i)/k, k)),
An example code of python3, when k is 3:
from functools import lru_cache
from itertools import accumulate
def solve(A, k, tar):
# only works when k = 3
assert k==3
presum = list(accumulate(A, initial=0))
@lru_cache(None)
def judge(i, j):
"""
find if s[i:j] can be full erased
"""
l,remainder = divmod(j-i,k)
if remainder != 0 or presum[j]-presum[i] != tar*l:
return False
if l<=1:
return True
# enumerate the last 3 elements to be erased
# # find triplets that sum to tar
for a1 in range(i, j, 3):
for a2 in range(a1+1, j, 3):
for a3 in range(a2+1, j, 3):
if A[a1]+A[a2]+A[a3]==tar:
prv = i
flag = True
for nxt in a1,a2,a3,j:
if not judge(prv, nxt):
flag = False
break
prv = nxt+1
if flag == True:
return True
return False
return judge(0,len(A))
print(solve([1,2,3,4,8,0],3,9))
additional problem
I also wonder if there is any specific algorithm when k is 3 and 2.
A testcase that when k=3 greedy doesn't work:
A=[5,5,5,1,9,7,3,0,10, 5,5,5, 10,0,3,7,9,1,5,5,5];tar=15;k=3