You may recall that an array arr
is a mountain array if and only if:
arr.length >= 3
- There exists some index
i
(0-indexed) with0 < i < arr.length - 1
such that:arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given an integer array arr
, return the length of the longest subarray, which is a mountain. Return 0
if there is no mountain subarray.
Example 1:
Input: arr = [2,1,4,7,3,2,5]
Output: 5
Approach
Java
public class LongestMountainArray {public static void main(String[] args) {int[] arr = { 2, 1, 4, 7, 3, 2, 5 };System.out.println(longestMountain(arr));}static int longestMountain(int[] A) {int up = 0, down = 0;int n = A.length;if (A.length < 3)return 0;int i = 1;int ans = Integer.MIN_VALUE;while (i < n) {up = 0;while (i < n && A[i - 1] < A[i]) {i++;up++;}down = 0;while (i < n && A[i - 1] > A[i]) {i++;down++;}if (i < n && A[i - 1] == A[i])i++;if (up > 0 && down > 0)ans = Math.max(ans, up + down + 1);}if (ans == Integer.MIN_VALUE)return 0;return ans;}}
C++
#include <bits/stdc++.h>using namespace std;int longestMountain(vector<int> &A){int up = 0, down = 0;int n = A.size();if (A.size() < 3)return 0;int i = 1;int ans = INT_MIN;while (i < n){up = 0;while (i < n && A[i - 1] < A[i]){i++;up++;}down = 0;while (i < n && A[i - 1] > A[i]){i++;down++;}if (i < n && A[i - 1] == A[i])i++;if (up > 0 && down > 0)ans = max(ans, up + down + 1);}if (ans == INT_MIN)return 0;return ans;}int main(){vector<int> arr = {2, 1, 4, 7, 3, 2, 5};cout << longestMountain(arr);return 0;}
No comments:
Post a Comment