-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem_1793_maximumScore.cc
86 lines (82 loc) · 1.63 KB
/
Problem_1793_maximumScore.cc
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <stack>
#include <vector>
using namespace std;
class Solution
{
public:
// 单调栈
int maximumScore1(vector<int>& nums, int k)
{
int n = nums.size();
vector<int> left(n, -1);
stack<int> st;
for (int i = 0; i < n; i++)
{
// 单调递增栈
while (!st.empty() && nums[i] <= nums[st.top()])
{
st.pop();
}
if (!st.empty())
{
left[i] = st.top();
}
st.push(i);
}
vector<int> right(n, n);
st = stack<int>();
for (int i = n - 1; i >= 0; i--)
{
while (!st.empty() && nums[i] <= nums[st.top()])
{
st.pop();
}
if (!st.empty())
{
right[i] = st.top();
}
st.push(i);
}
int ans = 0;
for (int i = 0; i < n; i++)
{
int h = nums[i];
// 在 i 左侧的小于 h 的最近元素的下标 left[i]
int l = left[i];
// 在 p 右侧的小于 h 的最近元素的下标 right[i]
int r = right[i];
// 注意 (l, k) 是开区间
if (l < k && k < r)
{
ans = std::max(ans, h * (r - l - 1));
}
}
return ans;
}
// 双指针
// TODO: figure it out.
int maximumScore2(vector<int>& nums, int k)
{
int n = nums.size();
int left = k - 1;
int right = k + 1;
int ans = 0;
for (int i = nums[k];; i--)
{
while (left >= 0 && nums[left] >= i)
{
left--;
}
while (right < n && nums[right] >= i)
{
right++;
}
ans = std::max(ans, (right - left + 1) * i);
if (left == -1 && right == n)
{
break;
}
}
return ans;
}
};