-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathmaximum-increasing-triplet-value.cpp
43 lines (41 loc) · 1.22 KB
/
maximum-increasing-triplet-value.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Time: O(nlogn)
// Space: O(n)
// bst, prefix sum
class Solution {
public:
int maximumTripletValue(vector<int>& nums) {
set<int> left;
vector<int> right(size(nums));
for (int i = size(nums) - 2; i >= 1; --i) {
right[i] = max(right[i + 1], nums[i + 1]);
}
int result = 0;
for (int i = 1; i + 1 < size(nums); ++i) {
left.emplace(nums[i - 1]);
auto it = left.lower_bound(nums[i]);
if (it != cbegin(left) && right[i] > nums[i]) {
result = max(result, *prev(it) - nums[i] + right[i]);
}
}
return result;
}
};
// Time: O(nlogn)
// Space: O(n)
// bst
class Solution2 {
public:
int maximumTripletValue(vector<int>& nums) {
multiset<int> left, right(cbegin(nums) + 1, cend(nums));
int result = 0;
for (int i = 1; i + 1 < size(nums); ++i) {
left.emplace(nums[i - 1]);
right.erase(right.find(nums[i]));
auto it = left.lower_bound(nums[i]);
if (it != cbegin(left) && *rbegin(right) > nums[i]) {
result = max(result, *prev(it) - nums[i] + *rbegin(right));
}
}
return result;
}
};