-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3640-trionic-array-ii.cpp
More file actions
60 lines (48 loc) · 1.53 KB
/
Copy path3640-trionic-array-ii.cpp
File metadata and controls
60 lines (48 loc) · 1.53 KB
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
class Solution {
public:
long long maxSumTrionic(vector<int>& nums) {
int n = nums.size();
long long ans = LLONG_MIN;
int i = 1;
while (i < n - 2) {
// Find strictly decreasing middle segment
int midL = i, midR = i;
long long midSum = nums[i];
while (midR + 1 < n && nums[midR + 1] < nums[midR]) {
midSum += nums[++midR];
}
// Need at least one decreasing step
if (midL == midR) {
i++;
continue;
}
// Expand left strictly increasing
long long leftSum = 0, bestLeft = LLONG_MIN;
int l = midL;
while (l - 1 >= 0 && nums[l - 1] < nums[l]) {
leftSum += nums[--l];
bestLeft = max(bestLeft, leftSum);
}
if (bestLeft == LLONG_MIN) {
i++;
continue;
}
// Expand right strictly increasing
long long rightSum = 0, bestRight = LLONG_MIN;
int r = midR;
while (r + 1 < n && nums[r + 1] > nums[r]) {
rightSum += nums[++r];
bestRight = max(bestRight, rightSum);
}
if (bestRight == LLONG_MIN) {
i++;
continue;
}
// Combine
ans = max(ans, bestLeft + midSum + bestRight);
// Jump i to avoid reprocessing
i = midR;
}
return ans;
}
};