Longest Peak

Prompt

Write a function that takes in an array of integers and returns the length of the longest peak in the array.

A peak is defined as adjacent integers in the array that are strictly increasing until they reach a tip (the highest value in the peak), at which point they become strictly decreasing. At least three integers are required to form a peak.

For example, the integers 1, 4, 10, 2 form a peak, but the integers 4, 0, 10 don’t and neither do the integers 1, 2, 2, 0. Similarly, the integers 1, 2, 3 don’t form a peak because there aren’t any strictly decreasing integers after the 3.

Sample Input

array = [1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3]

Sample Output

6 // 0, 10, 6, 5, -1, -3

Solution

import java.util.*;

class Program {
	//O(n) time | O(1) space
  public static int longestPeak(int[] array) {
    // Write your code here.
    int longestPeakLength = 0;
    int i = 1;
    while(i < array.length - 1) {
    	//search the peak point
			boolean isPeak = array[i - 1] < array[i] && array[i] > array[i + 1];
			if (!isPeak) continue;// A
    	// if (array[i] <= array[i - 1] || array[i] <= array[i + 1]) {
    	// 	i += 1;
    	// 	continue;
    	// }

    	int leftIdx = i - 2;
    	
    	while (leftIdx >= 0 && array[leftIdx] < array[leftIdx + 1]) {
    			leftIdx --;
    		}

    	int rightIdx = i + 2; // B 
    	while(rightIdx < array.length  && array[rightIdx] <  array[rightIdx - 1]) {
    			rightIdx ++;
    		}
    	

    	int currentPeakLength = rightIdx - leftIdx - 1;
    	longestPeakLength = currentPeakLength >= longestPeakLength ? currentPeakLength : longestPeakLength;
    	i = rightIdx;
    }
    return longestPeakLength;
  }
}

How to Bug Free

要把复杂的问题或者思考过程,拆解成几步,比如在isPeak这里,使用isPeak会比 >= 更加好理解

Why can’t I Solve this

见得少,我拿到这个题,想的是对每个数进行检查遍历,但是并不需要,只要找到某几个数,再遍历就可以,而找到某几个数的特征其实很好抽象出来,其实就是把题目翻译一下就可

Conclusion

# B

这个并不会溢出,因为并没有取i + 2 处的值

  • week review
  • Difficuity
  • status
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值