- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 41 lines of Python from the credited upstream file 2907.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class FenwickTree:2 def __init__(self, n: int):3 self.vals = [0] * (n + 1)4 5 def maximize(self, i: int, val: int) -> None:6 while i < len(self.vals):7 self.vals[i] = max(self.vals[i], val)8 i += FenwickTree.lowbit(i)9 10 def get(self, i: int) -> int:11 res = 012 while i > 0:13 res = max(res, self.vals[i])14 i -= FenwickTree.lowbit(i)15 return res16 17 @staticmethod18 def lowbit(i: int) -> int:19 return i & -i20 21 22class Solution:23 def maxProfit(self, prices: list[int], profits: list[int]) -> int:24 ans = -125 maxPrice = max(prices)26 maxProfitTree1 = FenwickTree(maxPrice)27 maxProfitTree2 = FenwickTree(maxPrice)28 29 for price, profit in zip(prices, profits):30 31 maxProfit1 = maxProfitTree1.get(price - 1)32 33 maxProfit2 = maxProfitTree2.get(price - 1)34 maxProfitTree1.maximize(price, profit)35 if maxProfit1 > 0:36 maxProfitTree2.maximize(price, profit + maxProfit1)37 if maxProfit2 > 0:38 ans = max(ans, profit + maxProfit2)39 40 return ans41