Maximum Drawdown in Python
Reversed version of 121. Best Time to Buy and Sell Stock
Rather than a "virtual problem" on Leetcode, calculating Maximum Drawdown(MDD) is an actual problem in reality.
Interestingly, this happens to be the "reversed" version of Leet code 121. Best Time to Buy and Sell Stock.
Key ideas
- We use l(left pointer) to track the MDD start
- We use r(right pointer) to track the MDD end
- Whenever
fund[r] >= fund[l], it means we have passed the drawdown, thus we reset left pointer as right pointer, so we can catch the next drawdown and compare if the new drawdown is severer than the current one
def maximum_drawdown (fund):
l, r = 0, 1
mdd = 0
while r < len(fund):
if fund[r] >= fund[l]:
l = r
else:
mdd = min(mdd, fund[r] - fund[l])
r += 1
return mdd
maximum_drawdown([1]) # 0
maximum_drawdown([1,2,3,4,5,6,7]) # 0
maximum_drawdown([5,4,3,3,2,1]) # -4
maximum_drawdown([7,5,1,2,6,4]) # -6
If you tweak it a bit, it's the solution of 121. Best Time to Buy and Sell Stock :)