LeetCode 845. Longest Mountain in Array

原题链接在这里:https://leetcode.com/problems/longest-mountain-in-array/

题目:

Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:

  • B.length >= 3
  • There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]

(Note that B could be any subarray of A, including the entire array A.)

Given an array A of integers, return the length of the longest mountain

Return 0 if there is no mountain.

Example 1:

Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.

Example 2:

Input: [2,2,2]
Output: 0
Explanation: There is no mountain.

Note:

  1. 0 <= A.length <= 10000
  2. 0 <= A[i] <= 10000

Follow up:

  • Can you solve it using only one pass?
  • Can you solve it in O(1) space?

题解:

Could do it with mutiple passes. One pass from left to right calculating up count. 

One pass from right to left calculating down count.

Then final pass calculate maximum.

The follow up says one pass with O(1) space. 

When A[i] == A[i-1], it is not mountain, i++.

First try counting up first, then try counting down. If both counts are positive, that means it is a mountain. Update res.

Time Complexity: O(n). n = A.length.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int longestMountain(int[] A) {
 3         int res = 0;
 4         int i = 1;
 5         int n = A.length;
 6         while(i<n){
 7             while(i<n && A[i]==A[i-1]){
 8                 i++;
 9             }
10             
11             int up = 0;
12             while(i<n && A[i]>A[i-1]){
13                 up++;
14                 i++;
15             }
16             
17             int down = 0;
18             while(i<n && A[i]<A[i-1]){
19                 down++;
20                 i++;
21             }
22             
23             if(up>0 && down>0){
24                 res = Math.max(res, up+down+1);
25             }
26         }
27         
28         return res;
29     }
30 }
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11361560.html