-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP1438.cpp
84 lines (80 loc) · 2.26 KB
/
P1438.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
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
#include "header.h"
#include <queue>
#include <vector>
class Solution {
public:
int longestSubarray(vector<int>& nums, int limit) {
if (nums.empty()) return 0;
int h,t;
int _M, _m, Mi, mi;
h = 0;
t = 1;
_M = _m = nums.front();
Mi=mi=h;
int ans = 1;
while (t<nums.size()) {
if (abs(nums[t]-nums[t-1])>limit) {
h=t;
t=h+1;
_M = _m = nums[h];
Mi = mi = h;
}
else if (nums[t]<=_M && nums[t]>=_m) {
t++;
}
else if (nums[t]>_M) {
if (nums[t]-_m <=limit) {
_M = nums[t];
Mi = t;
t++;
}
else {
h = mi+1;
_m = nums[h];
mi = h;
for (int i=h; i<t; i++) {
if (nums[i]<=_m) {
_m = nums[i];
mi = i;
}
}
}
}
else if (nums[t]<_m) {
if (_M-nums[t] <= limit) {
_m = nums[t];
mi = t;
t++;
}
else {
h = Mi+1;
_M = nums[h];
Mi = h;
for (int i=h; i<t; i++) {
if (nums[i]>=_M) {
_M = nums[i];
Mi = i;
}
}
}
}
if (t-h>ans) ans = t-h;
}
return ans;
}
};
int main() {
vector<int> nums;
int limit;
nums = {8,2,4,7}; limit = 4;
cout << Solution().longestSubarray(nums, limit) << endl;
nums = {10,1,2,4,7,2}; limit = 5;
cout << Solution().longestSubarray(nums, limit) << endl;
nums = {4,2,2,2,4,4,2,2}; limit = 0;
cout << Solution().longestSubarray(nums, limit) << endl;
nums = {}; limit = 4;
cout << Solution().longestSubarray(nums, limit) << endl;
nums = {8,2}; limit = 4;
cout << Solution().longestSubarray(nums, limit) << endl;
return 0;
}