This problem can be done with DP but there’s no need for it because it can be done with just a sliding window that too in O(N) time. (I’ll update here with the DP solution some time in the future)
We maintain a sliding window and move it across over the string S. Whenever we move over our limit that is the maxCost
, we decrease our window from the left.
Code:
Python3
Big O Analysis
-
Runtime
The runtime complexity here is
O(N)
as since we would be iterating the string once. -
Memory
The memory usage is
O(1)
since we do not use any datastructure.
— A