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