Heres the question: Profitable Triplets
Given the arrays prices and profits of length n, find the max profit you can make.
Profit = profit[i] + profit[j] + profit[k] given prices[i] < prices[j] < prices[k]
(0 <= n <= 4k)
I tried to solve it with memoized dp
from functools import cache
def profitable_triplets(profits, prices):
@cache
def dp(i=0, lower_bound=0, remaining=3):
if not remaining: return 0
if i == len(profits): return float('-inf')
pick = float('-inf')
if prices[i] > lower_bound:
pick = profit[i] + dp(i+1, prices[i], remaining -1)
skip = dp(i+1, lower_bound, remaining)
return max(pick, skip)
return dp()This failed on 6/12 test cases because of the error "maximum recursion depth reached"
I used sys to change the maximum depth to 10k but the last test case still failed with that error. Same even if I changed the max depth to 100k (although im not sure if python actually allowed me to do that)
I have never had this problem on leetcode, but its the second time I have ran into this on hackerrank while using memoized dp. Should I just stick to bottom up?
Or is my solution wrong? I thought it was ok since worse case is 48 million states. (4k indicies, 4k possible lower bounds, 3 states for remaining)