Leet Code Intutions
1
Recursive:
Start with 0, -1.
If an element in the index is greater than the previous one, include it or skip the element.
Find max(include and exclude).
Base: index == len(nums), return 0.
Tabulation DP: (Optimized)
Start with each element as a subsequence of length 1 in a [].
For each element in the sequence, look for pre elements and if the current element is greater than prev ele then update [].
The Max element in list is Longest subsequence.
Memoization DP:
Avoid recalculation and initialize a Dict.
Fill the dict with the Longest sequence up to the point.
2
Recursive:
start with current_sum =0
For each number in the list:
you can either ADD(+)
Or Subtract (-)
When Curr_Sum == Target then return 1 else, return 0
return the total of ADD+Subtract; this would be the "total number of Targeted sum."
Solution
Memoization DP:
Avoid recalculation and initialize a Dict.
Fill the dict with the (index,curr_sum) = ADD+Subtract.
Now return the Dict[ (index,curr_sum)]
Tabulation DP:
3
Recursive:
Base case:
when the index is 0 you will return nums[index] (only one house to rob)
when the index is less than 0 return 0 (Invalid case, No house)
Start with the end of the list. When you go for an index you can include or exclude
Include = element at the index + f(index -2) (skip the adjacent house)
Exclude = 0 + f(index -1) (Skip the current house and check the previous one)
return the maximum(include, exclude)
Memoization DP:
To avoid re-calculation, Use an array/dict to keep track of the maximum at that index.
When the index is in Dict, return the memo[index] value.
Tabulation DP:
We fill a DP array
Dp[i] stores a max money robbed until that house.
At each step, we can decide to include or exclude the current house.
Include: adding money from
i-2
since adjacent houses can't be robbed.Exclude : taking the value from
dp[i-1]
.
return last element from Dp array.
Space optimized :
Let's use
prev as the first element in the list.
prev2 as 0
with the same bottom-up approach but without storing results in an array.
include = curr_element and if index is greater than 1 add prev2.
exclude = prev
curr_max = max(include, exclude)
Swap prev to prev2, curr_max to prev.
Return prev.
4
House Robber II Same as House Robber
Recursive Memoization DP Tabulation DP Space optimized :
Just divide the array into
array[1:] ( 0 element not included)
array[:-1] (Last element not included)
5
Space Optimized :
start with initializing buy , sell to zero
Start from last element :
buy if max(buy, sell - day_price )
sell if max(sell, buy + price -fee)
return buy -> holds the maximum profit without holding a stock at the end.
Last updated