@cache for memoization
we can use []@cache
](https://docs.python.org/3/library/functools.html#functools.cache) for memoization in python
MUST SEE: https://leetcode.com/discuss/general-discussion/1561340/has-anyone-used-python-cache-in-an-interview Documentation: https://docs.python.org/3/library/functools.html#functools.cache
Exampl question: https://leetcode.com/problems/maximum-subarray/submissions/
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
@cache # memoization
def maxStartingAt(i):
return (
max(nums[i], nums[i] + maxStartingAt(i + 1))
if i < len(nums) - 1
else nums[i]
)
return max(maxStartingAt(i) for i in range(len(nums)))
⏫ above code its just recursion, only @cache is added before the recursive function declaration.
It will be very benificial in Dynamic Programming when we dont have much time for creating memoization
Another Example for same Problem:
recursion with @cache for memoization
class Solution:
def maxSubArray(self, nums):
@cache
def solve(i, must_pick):
if i >= len(nums): return 0 if must_pick else -inf
return max(nums[i] + solve(i+1, True), 0 if must_pick else solve(i+1, False))
return solve(0, False)
recursion WITHOUT @cache will also work but gives TLE
class Solution:
def maxSubArray(self, nums):
def solve(i, must_pick):
if i >= len(nums): return 0 if must_pick else -inf
return max(nums[i] + solve(i+1, True), 0 if must_pick else solve(i+1, False))
return solve(0, False)