Prompt
Write a function that takes in an array of integers and returns the length of the longest peak in the array.
A peak is defined as adjacent integers in the array that are strictly increasing until they reach a tip (the highest value in the peak), at which point they become strictly decreasing. At least three integers are required to form a peak.
For example, the integers 1, 4, 10, 2 form a peak, but the integers 4, 0, 10 don’t and neither do the integers 1, 2, 2, 0. Similarly, the integers 1, 2, 3 don’t form a peak because there aren’t any strictly decreasing integers after the 3.
Sample Input
array = [1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3]
Sample Output
6 // 0, 10, 6, 5, -1, -3
Solution
import java.util.*;
class Program {
//O(n) time | O(1) space
public static int longestPeak(int[] array) {
// Write your code here.
int longestPeakLength = 0;
int i = 1;
while(i < array.length - 1) {
//search the peak point
boolean isPeak = array[i - 1] < array[i] && array[i] > array[i + 1];
if (!isPeak) continue;// A
// if (array[i] <= array[i - 1] || array[i] <= array[i + 1]) {
// i += 1;
// continue;
// }
int leftIdx = i - 2;
while (leftIdx >= 0 && array[leftIdx] < array[leftIdx + 1]) {
leftIdx --;
}
int rightIdx = i + 2; // B
while(rightIdx < array.length && array[rightIdx] < array[rightIdx - 1]) {
rightIdx ++;
}
int currentPeakLength = rightIdx - leftIdx - 1;
longestPeakLength = currentPeakLength >= longestPeakLength ? currentPeakLength : longestPeakLength;
i = rightIdx;
}
return longestPeakLength;
}
}
How to Bug Free
要把复杂的问题或者思考过程,拆解成几步,比如在isPeak这里,使用isPeak会比 >= 更加好理解
Why can’t I Solve this
见得少,我拿到这个题,想的是对每个数进行检查遍历,但是并不需要,只要找到某几个数,再遍历就可以,而找到某几个数的特征其实很好抽象出来,其实就是把题目翻译一下就可
Conclusion
# B
这个并不会溢出,因为并没有取i + 2 处的值
- week review
- Difficuity
- status