-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbiotonic subarray.cpp
More file actions
89 lines (83 loc) · 2.91 KB
/
biotonic subarray.cpp
File metadata and controls
89 lines (83 loc) · 2.91 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
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
87
88
89
class Solution {
public:
vector<int> findBitonicSubarray(vector<int> const &nums) {
if (nums.empty()) {
return {};
}
int min = nums[0];
int max = nums[0];
int count1 = 1; // Start with 1 since single element is valid
int len = nums.size();
// Variables to track the longest sequence
int maxLen = 1;
int start = 0;
int bestStart = 0, bestEnd = 0;
bool isIncreasing = true;
for (int i = 1; i < len; i++) {
if (isIncreasing) {
if (nums[i] > nums[i-1]) {
// Still increasing
count1++;
}
else if (nums[i] < nums[i-1]) {
// Start decreasing
isIncreasing = false;
count1++;
}
else { // Equal elements case
// Save current sequence if it's the longest
if (count1 > maxLen) {
maxLen = count1;
bestStart = start;
bestEnd = i - 1;
}
// Start new sequence from current position
start = i;
count1 = 1;
}
}
else { // In decreasing phase
if (nums[i] < nums[i-1]) {
// Continue decreasing
count1++;
}
else if (nums[i] > nums[i-1]) {
// Save current sequence if it's the longest
if (count1 > maxLen) {
maxLen = count1;
bestStart = start;
bestEnd = i - 1;
}
// Start new sequence from previous position
start = i - 1;
count1 = 2;
isIncreasing = true;
}
else { // Equal elements case
// Save current sequence if it's the longest
if (count1 > maxLen) {
maxLen = count1;
bestStart = start;
bestEnd = i - 1;
}
// Start new sequence
start = i;
count1 = 1;
isIncreasing = true;
}
}
}
// Check final sequence
if (count1 > maxLen) {
maxLen = count1;
bestStart = start;
bestEnd = len - 1;
}
// Create result vector
vector<int> result;
for (int i = bestStart; i <= bestEnd; i++) {
result.push_back(nums[i]);
}
return result;
}
};