Maximum Profitable Triplets With Increasing Prices II
Time O(nlogn) · Space O(n) · Official statement on LeetCode
Solutions
// Time: O(nlogn)
// Space: O(n)
// prefix sum, bst, binary search, mono stack
class Solution {
public:
int maxProfit(vector<int>& prices, vector<int>& profits) {
static const int NEG_INF = numeric_limits<int>::min();
const auto& query = [](const auto& bst, const auto& k) {
const auto it = bst.lower_bound(pair(k, 0));
return it != begin(bst) ? prev(it)->second : NEG_INF;
};
const auto& update = [](auto& bst, const auto& k, const auto& v) {
const auto it = bst.lower_bound(pair(k, 0));
if (it != end(bst) && it->first == k) {
if (!(it->second < v)) {
return;
}
bst.erase(it);
} else if (!(it == begin(bst) || prev(it)->second < v)) {
return;
}
const auto [jt, _] = bst.emplace(k, v);
while (next(jt) != end(bst) && next(jt)->second <= jt->second) {
bst.erase(next(jt));
}
};
int result = NEG_INF;
set<pair<int, int>> bst1, bst2;
for (int i = 0; i < size(prices); ++i) {
const int mx2 = query(bst2, prices[i]);
if (mx2 != NEG_INF) {
result = max(result, mx2 + profits[i]);
}
update(bst1, prices[i], profits[i]);
const int mx1 = query(bst1, prices[i]);
if (mx1 != NEG_INF) {
update(bst2, prices[i], mx1 + profits[i]);
}
}
return result != NEG_INF ? result : -1;
}
};
// Time: O(nlogn)
// Space: O(n)
// prefix sum, bst, binary search, mono stack
class Solution2 {
public:
int maxProfit(vector<int>& prices, vector<int>& profits) {
static const int NEG_INF = numeric_limits<int>::min();
vector<int> right(size(prices), NEG_INF);
set<pair<int, int>> bst;
for (int i = size(prices) - 1; i >= 0; --i) {
const auto it = bst.lower_bound(pair(-prices[i], 0));
if (it != begin(bst)) {
right[i] = prev(it)->second;
}
if (!(it == begin(bst) || prev(it)->second < profits[i])) {
continue;
}
const auto [jt, _] = bst.emplace(-prices[i], profits[i]);
while (next(jt) != end(bst) && next(jt)->second <= jt->second) {
bst.erase(next(jt));
}
}
int result = NEG_INF;
bst.clear();
for (int i = 0; i < size(prices); ++i) {
const auto it = bst.lower_bound(pair(prices[i], 0));
if (it != begin(bst)) {
if (prev(it)->second != NEG_INF && right[i] != NEG_INF) {
result = max(result, prev(it)->second + profits[i] + right[i]);
}
}
if (!(it == begin(bst) || prev(it)->second < profits[i])) {
continue;
}
const auto [jt, _] = bst.emplace(prices[i], profits[i]);
while (next(jt) != end(bst) && next(jt)->second <= jt->second) {
bst.erase(next(jt));
}
}
return result != NEG_INF ? result : -1;
}
};
// Time: O(nlogn)
// Space: O(n)
// prefix sum, bit, fenwick tree
class Solution3 {
public:
int maxProfit(vector<int>& prices, vector<int>& profits) {
static const int NEG_INF = numeric_limits<int>::min();
unordered_set<int> prices_set(cbegin(prices), cend(prices));
vector<int> sorted_prices(cbegin(prices_set), cend(prices_set));
sort(begin(sorted_prices), end(sorted_prices));
unordered_map<int, int> price_to_idx;
for (int i = 0; i < size(sorted_prices); ++i) {
price_to_idx[sorted_prices[i]] = i;
}
int result = NEG_INF;
const auto& fn = [](int a, int b) {
return max(a, b);
};
BIT bit1(size(price_to_idx), NEG_INF, fn), bit2(size(price_to_idx), NEG_INF, fn);
for (int i = 0; i < size(prices); ++i) {
const int mx2 = bit2.query(price_to_idx[prices[i]] - 1);
if (mx2 != NEG_INF) {
result = max(result, mx2 + profits[i]);
}
bit1.update(price_to_idx[prices[i]], profits[i]);
const int mx1 = bit1.query(price_to_idx[prices[i]] - 1);
if (mx1 != NEG_INF) {
bit2.update(price_to_idx[prices[i]], mx1 + profits[i]);
}
}
return result != NEG_INF ? result : -1;
}
private:
class BIT {
public:
BIT(int n, int val, const function<int (int, int)> fn)
: bit_(n + 1, val),
fn_(fn) { // 0-indexed
}
void update(int i, int val) {
++i;
for (; i < size(bit_); i += lower_bit(i)) {
bit_[i] = fn_(bit_[i], val);
}
}
int query(int i) const {
++i;
int total = bit_[0];
for (; i > 0; i -= lower_bit(i)) {
total = fn_(total, bit_[i]);
}
return total;
}
private:
int lower_bit(int i) const {
return i & -i;
}
vector<int> bit_;
const function<int (int, int)> fn_;
};
};
// Time: O(nlogn)
// Space: O(n)
// prefix sum, segment tree
class Solution4 {
public:
int maxProfit(vector<int>& prices, vector<int>& profits) {
static const int NEG_INF = numeric_limits<int>::min();
unordered_set<int> prices_set(cbegin(prices), cend(prices));
vector<int> sorted_prices(cbegin(prices_set), cend(prices_set));
sort(begin(sorted_prices), end(sorted_prices));
unordered_map<int, int> price_to_idx;
for (int i = 0; i < size(sorted_prices); ++i) {
price_to_idx[sorted_prices[i]] = i;
}
int result = NEG_INF;
SegmentTree st1(size(price_to_idx)), st2(size(price_to_idx));
for (int i = 0; i < size(prices); ++i) {
const int mx2 = st2.query(0, price_to_idx[prices[i]] - 1);
if (mx2 != NEG_INF) {
result = max(result, mx2 + profits[i]);
}
st1.update(price_to_idx[prices[i]], profits[i]);
const int mx1 = st1.query(0, price_to_idx[prices[i]] - 1);
if (mx1 != NEG_INF) {
st2.update(price_to_idx[prices[i]], mx1 + profits[i]);
}
}
return result != NEG_INF ? result : -1;
}
private:
class SegmentTree {
private:
const int NEG_INF = numeric_limits<int>::min();
public:
explicit SegmentTree(int N)
: tree(N > 1 ? 1 << (__lg(N - 1) + 2) : 2, NEG_INF),
base(N > 1 ? 1 << (__lg(N - 1) + 1) : 1) {
}
void update(int i, int h) {
int x = base + i;
tree[x] = max(tree[x], h);
while (x > 1) {
x /= 2;
tree[x] = max(tree[x * 2], tree[x * 2 + 1]);
}
}
int query(int L, int R) {
int result = NEG_INF;
if (L > R) {
return result;
}
L += base;
R += base;
for (; L <= R; L /= 2, R /= 2) {
if (L & 1) {
result = max(result, tree[L]);
++L;
}
if ((R & 1) == 0) {
result = max(tree[R], result);
--R;
}
}
return result;
}
vector<int> tree;
int base;
};
};
// Time: O(nlogn)
// Space: O(n)
// prefix sum, segment tree
class Solution5 {
public:
int maxProfit(vector<int>& prices, vector<int>& profits) {
static const int NEG_INF = numeric_limits<int>::min();
unordered_set<int> prices_set(cbegin(prices), cend(prices));
vector<int> sorted_prices(cbegin(prices_set), cend(prices_set));
sort(begin(sorted_prices), end(sorted_prices));
unordered_map<int, int> price_to_idx;
for (int i = 0; i < size(sorted_prices); ++i) {
price_to_idx[sorted_prices[i]] = i;
}
vector<int> right(size(prices), NEG_INF);
SegmentTree st2(size(price_to_idx));
for (int i = size(prices) - 1; i >= 0; --i) {
right[i] = st2.query(price_to_idx[prices[i]] + 1, size(price_to_idx) - 1);
st2.update(price_to_idx[prices[i]], profits[i]);
}
int result = NEG_INF;
vector<int> left(size(prices), NEG_INF);
SegmentTree st1(size(price_to_idx));
for (int i = 0; i < size(prices); ++i) {
const int left = st1.query(0, price_to_idx[prices[i]] - 1);
if (left != NEG_INF && right[i] != NEG_INF) {
result = max(result, left + profits[i] + right[i]);
}
st1.update(price_to_idx[prices[i]], profits[i]);
}
return result != NEG_INF ? result : -1;
}
private:
class SegmentTree {
private:
const int NEG_INF = numeric_limits<int>::min();
public:
explicit SegmentTree(int N)
: tree(N > 1 ? 1 << (__lg(N - 1) + 2) : 2, NEG_INF),
base(N > 1 ? 1 << (__lg(N - 1) + 1) : 1) {
}
void update(int i, int h) {
int x = base + i;
tree[x] = max(tree[x], h);
while (x > 1) {
x /= 2;
tree[x] = max(tree[x * 2], tree[x * 2 + 1]);
}
}
int query(int L, int R) {
int result = NEG_INF;
if (L > R) {
return result;
}
L += base;
R += base;
for (; L <= R; L /= 2, R /= 2) {
if (L & 1) {
result = max(result, tree[L]);
++L;
}
if ((R & 1) == 0) {
result = max(tree[R], result);
--R;
}
}
return result;
}
vector<int> tree;
int base;
};
};
Beginner Explanation
What is Maximum Profitable Triplets With Increasing Prices II?
Maximum Profitable Triplets With Increasing Prices II (LeetCode #2921) is a Hard problem that primarily trains binary search tree.
How to think about it
- Restate the goal in your own words before coding.
- Work a tiny example by hand so the invariant becomes obvious.
- Identify the pattern — this problem aligns with prefix sum, sorted list, binary search, stack, fenwick tree, and segment tree.
- Only then translate the idea into code.
Why this problem matters
Hard problems force you to combine patterns and prove complexity carefully — interview gold. Official solution notes mention: Prefix Sum, Sorted List, BST, Binary Search.
AlgoForge explanations are original teaching notes. Always open the official problem statement on LeetCode for constraints and examples.
Interview Walkthrough
Interview approach for Maximum Profitable Triplets With Increasing Prices II
Opening (30–60 seconds)
- Clarify inputs/outputs and edge cases (empty input, single element, duplicates, overflow).
- State a brute force so the interviewer knows you can solve it naively.
- Propose the optimal direction tied to prefix sum, sorted list, binary search, stack, fenwick tree, and segment tree.
Core solution narrative
- Define the state you track (pointers, DP cell, set membership, stack top, etc.).
- Explain the transition when you process the next element.
- Call out time (O(nlogn)) and space (O(n)) before coding.
- Code cleanly; narrate variable names.
What interviewers listen for
- Correctness on edge cases
- Complexity honesty
- Ability to discuss trade-offs (e.g., hash map space vs. sort + two pointers)
Follow-up questions they may ask
- Can you solve it with less memory?
- What if the input stream is infinite / doesn't fit in RAM?
- How would tests look for adversarial inputs?
Optimized Approach
Optimized solution notes
The reference solutions on AlgoForge target O(nlogn) time and O(n) space.
Pattern focus: prefix sum, sorted list, binary search, stack, fenwick tree, and segment tree
Use the pattern as a checklist:
- prefix sum — confirm the invariant holds after each step
- sorted list — confirm the invariant holds after each step
- binary search — confirm the invariant holds after each step
- stack — confirm the invariant holds after each step
- fenwick tree — confirm the invariant holds after each step
- segment tree — confirm the invariant holds after each step
Multiple methods appear in the source solutions — compare them and explain when each is preferable.
Implementation tips
- Prefer readable names over micro-optimizations in interviews.
- Extract helpers only when they clarify (e.g., expand-around-center, DFS visit).
- After AC-level logic, re-scan for off-by-one and null checks.
Complexity Analysis
Complexity
| Measure | Bound |
|---|---|
| Time | O(nlogn) |
| Space | O(n) |
How to justify this in an interview
- Time: count loops, map/set operations, and recursive branching; state average vs worst case if relevant.
- Space: include hash maps, recursion stack, and output allocation when the problem asks for it.
If your implementation differs from the reference, re-derive big-O from your code — never memorize a complexity you cannot defend.
Common Mistakes
Common mistakes on Maximum Profitable Triplets With Increasing Prices II
- Skipping edge cases — empty collections, single-element inputs, max constraints.
- Wrong invariant for prefix sum, sorted list, binary search, stack, fenwick tree, and segment tree — updating state too early or too late.
- Mutating input unexpectedly when the problem forbids it.
- Off-by-one in windows, ranges, or binary search bounds.
- Ignoring overflow / precision for integer arithmetic problems.
- Overengineering — jumping to an advanced structure when a simpler approach works.
Alternative Approaches
Alternatives
The source file includes more than one method. Compare:
- Primary optimized path — best complexity for typical interviews.
- Secondary approach — often brute force, sorting-based, or space-optimized variant.
Practice articulating when you would pick each (constraints, readability, follow-ups).
Edge Cases
Edge cases checklist
- Minimum input size
- Maximum input size / time limits
- Duplicates and already-sorted input
- Negative numbers / zeros (if applicable)
- Disconnected structures (graphs/trees)
- Single path vs branching recursion depth
Pattern Recognition
Spotting this pattern
Signal phrases that point to prefix sum, sorted list, binary search, stack, fenwick tree, and segment tree:
- Sorted input or ability to sort without changing the answer class
- Need for contiguous subarray / substring → consider sliding window
- Need for O(1) membership → hash set/map
- Optimal substructure + overlapping subproblems → DP
- Connectivity / components → graph DFS/BFS or Union-Find
Primary topics: binary search tree.
Follow-up Interview Questions
Follow-ups
- How does the solution change if the input is a stream?
- Can you solve it in-place?
- What if duplicates must be handled differently?
- How would you parallelize the approach?
- Design tests that would break a buggy implementation.
Practice Recommendations
What to practice next
- Re-solve Maximum Profitable Triplets With Increasing Prices II in a second language (cpp, python).
- Drill 3–5 more problems tagged binary search tree.
- Teach the solution out loud in under 5 minutes.
- Add this problem to your revision calendar in 3 days and 14 days.
Visualization
Study checklist
- Read the official problem statement on LeetCode
- Solve on paper / whiteboard first
- Implement the prefix sum, sorted list, binary search, stack, fenwick tree, and segment tree approach
- Verify edge cases from the checklist
- State time and space complexity aloud
- Compare with the AlgoForge reference solution
- Schedule a revision session
Revision notes
Maximum Profitable Triplets With Increasing Prices II (#2921) — Hard. Pattern: prefix sum, sorted list, binary search, stack, fenwick tree, and segment tree. Complexity: O(nlogn) time / O(n) space. Re-derive the invariant before coding.
FAQs
What is the time complexity of Maximum Profitable Triplets With Increasing Prices II?+
The reference solutions aim for O(nlogn) time and O(n) space. Always re-derive complexity from the code you write in the interview.
What pattern does Maximum Profitable Triplets With Increasing Prices II use?+
It primarily maps to prefix sum, sorted list, binary search, stack, fenwick tree, and segment tree, within the broader topic of binary search tree.
Is Maximum Profitable Triplets With Increasing Prices II good for interviews?+
Yes — as a Hard problem it is a solid practice target. Pair it with related problems in the same pattern family for spaced repetition.
Where can I read the official statement?+
Open the official LeetCode page for constraints and examples: https://leetcode.com/problems/maximum-profitable-triplets-with-increasing-prices-ii/