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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值