Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2d09328

Browse files
Create 3691.Maximum-Total-Subarray-Value-II_v1.cpp
1 parent c288887 commit 2d09328

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
using LL = long long;
2+
class Solution {
3+
public:
4+
long long maxTotalValue(vector<int>& nums, int k) {
5+
int n = nums.size(), K = log2(n) + 1;
6+
7+
int mn[50005][35]; memset(mn, 0x3f, sizeof(mn));
8+
int mx[50005][35]; memset(mx, 0xcf, sizeof(mx));
9+
for (int i = 0; i < n; i++) mn[i][0] = mx[i][0] = nums[i];
10+
for (int k = 1; k <= K; k++) {
11+
for (int i = 0; i+(1<<k)-1 < n; i++) {
12+
mn[i][k] = min(mn[i][k-1], mn[i+(1<<(k-1))][k-1]);
13+
mx[i][k] = max(mx[i][k-1], mx[i+(1<<(k-1))][k-1]);
14+
}
15+
}
16+
17+
auto GetDiff = [&](int L, int R){
18+
int k = log2(R-L+1);
19+
return max(mx[L][k], mx[R-(1<<k)+1][k]) - min(mn[L][k], mn[R-(1<<k)+1][k]);
20+
};
21+
22+
auto count_ge = [&](int th) {
23+
int count = 0;
24+
int j = 0;
25+
for (int i=0; i<n; i++) {
26+
while (j<n && GetDiff(i,j)<th) j++;
27+
count += n-j;
28+
}
29+
return count;
30+
};
31+
32+
int lo = 0, hi = 2e9;
33+
while (lo < hi) {
34+
int mid = hi-(hi-lo)/2;
35+
if (count_ge(mid) >= k)
36+
lo = mid;
37+
else
38+
hi = mid-1;
39+
}
40+
LL th = lo;
41+
42+
LL ret_g = 0;
43+
LL count_g = 0;
44+
for (int i=0; i<n; i++) {
45+
int l = i, r = n-1;
46+
while (l<r) {
47+
int mid = l+(r-l)/2;
48+
if (GetDiff(i,mid)>th)
49+
r = mid;
50+
else
51+
l = mid+1;
52+
}
53+
if (GetDiff(i, r) > th) {
54+
count_g += n-r;
55+
for (int j=r; j<n; j++)
56+
ret_g += GetDiff(i, j);
57+
}
58+
}
59+
60+
LL ret = ret_g + th * (k-count_g);
61+
62+
return ret;
63+
64+
}
65+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /