funclongestMountain(arr []int)int { n := len(arr) left := make([]int, n) for i := 1; i < n; i++ { if arr[i-1] < arr[i] { left[i] = left[i-1] + 1 } } right := make([]int, n) for i := n - 2; i >= 0; i-- { if arr[i+1] < arr[i] { right[i] = right[i+1] + 1 } } ans := 0 for i, l := range left { r := right[i] if l > 0 && r > 0 && l+r+1 > ans { ans = l + r + 1 } } return ans }
classSolution { public: intlongestMountain(vector<int>& arr){ int n = arr.size(); int ans = 0; int left = 0; while (left + 2 < n) { int right = left + 1; if (arr[left] < arr[left + 1]) { while (right + 1 < n && arr[right] < arr[right + 1]) { ++right; } if (right < n - 1 && arr[right] > arr[right + 1]) { while (right + 1 < n && arr[right] > arr[right + 1]) { ++right; } ans = max(ans, right - left + 1); } else { ++right; } } left = right; } return ans; } };
classSolution { publicintlongestMountain(int[] arr) { intn= arr.length; intans=0; intleft=0; while (left + 2 < n) { intright= left + 1; if (arr[left] < arr[left + 1]) { while (right + 1 < n && arr[right] < arr[right + 1]) { ++right; } if (right < n - 1 && arr[right] > arr[right + 1]) { while (right + 1 < n && arr[right] > arr[right + 1]) { ++right; } ans = Math.max(ans, right - left + 1); } else { ++right; } } left = right; } return ans; } }
[sol2-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution: deflongestMountain(self, arr: List[int]) -> int: n = len(arr) ans = left = 0 while left + 2 < n: right = left + 1 if arr[left] < arr[left + 1]: while right + 1 < n and arr[right] < arr[right + 1]: right += 1 if right < n - 1and arr[right] > arr[right + 1]: while right + 1 < n and arr[right] > arr[right + 1]: right += 1 ans = max(ans, right - left + 1) else: right += 1 left = right return ans
funclongestMountain(arr []int)int { n := len(arr) ans := 0 left := 0 for left+2 < n { right := left + 1 if arr[left] < arr[left+1] { for right+1 < n && arr[right] < arr[right+1] { right++ } if right < n-1 && arr[right] > arr[right+1] { for right+1 < n && arr[right] > arr[right+1] { right++ } if right-left+1 > ans { ans = right - left + 1 } } else { right++ } } left = right } return ans }