I am trying to find out the longest peak length in an array.
Example: Array: [1, 2, 3, 2, 1, 1] Peak Length: 5 (1,2,3,2,1)
I have used the following code to find out the longest peak in an array:
using namespace std;
int longestPeak(vector<int> array) {
int longestPeak = 0;
int idx = 1;
*`//In the while loop below, if I change the condition to (idx < (array.size() - 1)), it throws a segmentation fault'*
while (idx < int(array.size() - 1)){
bool isPeak = array[idx] > array[idx - 1] and array[idx] > array[idx + 1];
if (!isPeak){
idx += 1;
continue;
}
int leftIdx = idx - 2;
while (leftIdx >= 0 and array[leftIdx] < array[leftIdx + 1])
leftIdx -= 1;
int rightIdx = idx + 2;
while (rightIdx < array.size() and array[rightIdx] < array[rightIdx - 1])
rightIdx += 1;
int currentPeak = rightIdx - leftIdx - 1;
longestPeak = max(currentPeak, longestPeak);
idx = rightIdx;
}
return longestPeak;
}
In the first while loop below, if I change the condition to (idx < (array.size() - 1)), it throws a segmentation fault.
Please help me understand the reason behind this issue.