Link: https://leetcode.com/problems/longest-mountain-in-array/
Solution 1:
- find peak
- go left to find the increasing start index
- go right to find the decreasing end index
- calculate mountain length
- if the current mountain length is bigger than previous max, replace max
/**
* @param {number[]} arr
* @return {number}
*/
var longestMountain = function(arr) {
var max = 0;
for(var i = 1; i < arr.length - 1; i++)
{
if (arr[i - 1] < arr[i] && arr[i] > arr[i + 1])
{
var l = i - 1;
var r = i + 1;
while(arr[l - 1] < arr[l])
l--;
while(arr[r] > arr[r+1])
r++;
var newMax = r - l + 1;
if (newMax > max)
max = newMax;
}
}
return max;
};
Leave a Reply