- 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
- 55 lines of C++ from the credited upstream file 2921.cpp.
- The implementation visibly relies on sequence storage.
- 3 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 public:3 FenwickTree(int n) : vals(n + 1) {}4 5 void maximize(int i, int val) {6 while (i < vals.size()) {7 vals[i] = max(vals[i], val);8 i += lowbit(i);9 }10 }11 12 int get(int i) const {13 int res = 0;14 while (i > 0) {15 res = max(res, vals[i]);16 i -= lowbit(i);17 }18 return res;19 }20 21 private:22 vector<int> vals;23 24 static int lowbit(int i) {25 return i & -i;26 }27};28 29class Solution {30 public:31 32 int maxProfit(vector<int>& prices, vector<int>& profits) {33 const int maxPrice = ranges::max(prices);34 int ans = -1;35 FenwickTree maxProfitTree1(maxPrice);36 FenwickTree maxProfitTree2(maxPrice);37 38 for (int i = 0; i < prices.size(); ++i) {39 const int price = prices[i];40 const int profit = profits[i];41 42 const int maxProfit1 = maxProfitTree1.get(price - 1);43 44 const int maxProfit2 = maxProfitTree2.get(price - 1);45 maxProfitTree1.maximize(price, profit);46 if (maxProfit1 > 0)47 maxProfitTree2.maximize(price, profit + maxProfit1);48 if (maxProfit2 > 0)49 ans = max(ans, profit + maxProfit2);50 }51 52 return ans;53 }54};55