You will be given an input array containing a list of integers. A peak is defined as adjacent integers in the array that are strictly increasing until they reach a tip, at which point they become strictly decreasing. At least three integers are required to form a peak.
Examples
1, ,4, 10, 2 , this list forms a peak.
4, 0, 10, this list does not form a peak
1, 2, 2, 0 this list does not form a peak due to not strictly increasing.
3, 4, 0 this list does form a peak
We need at least three integers to form a peak
Solution
To solve this problem instead of intuitively iterating through the array simply counting the peaks as well as their lengths it would be best to iterate through the array left to right and for each element look at the left and right value, if the left and right values area strictly less than the current value then we know we’ve reached a peak.
After identifying all the peaks in the array, what we can do is see how long the peaks are and compare the lengths and return the longest one. We can start at the tips of these peaks and see how far out to the left and how far out to the right we can go until we’ve reach a no longer strictly decreasing number.
Time complexity: O(N) , The first iteration where we find the peaks requires us to go through each element, during our second iteration where we count the length of these peaks, there will be values that we will skip over since not all values can be considered a peak. Thus in total the worst possible time is O of N.
It’s important to note that you can also combine these two tasks into one iteration.
Space Complexity: O(1) , at most we will need a variable to hold the current max length of each peak.