I recently got 1423. Maximum Points You Can Obtain from Cards as my interview question.
I gave a brute force recursive solution similar to the subsets and combinations problem as follows:
class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
def maxHelper(nums, curr_sum, k, result, choices, idx):
if idx==k:
if curr_sum>result[0]:
result[0] = curr_sum
return
for index in range(2):
# choose
curr_sum += nums[choices[index]]
# explore
if index==0:
maxHelper(nums[choices[index]+1:], curr_sum, k, result, choices, idx+1)
if index==1:
maxHelper(nums[:choices[index]], curr_sum, k, result, choices, idx+1)
# un-choose
curr_sum -= nums[choices[index]]
if len(cardPoints)==k:
return sum(cardPoints)
result = [float('-Inf')]
choices = {0:0, 1:-1}
maxHelper(cardPoints, 0, k, result, choices, 0)
return result[0]Could anyone tell me how do I memoize this solution? While there are other methods like sliding window etc., I specifically wanted to know if this particular solution can be memoized and converted into a DP solution or not.
Appreciate your time.