Longest Peak
2021/7/14 6:06:19
本文主要是介绍Longest Peak,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
refer to: https://www.algoexpert.io/questions/Longest%20Peak
Problem Statement
Sample
Analysis
Code
1 def longestPeak(array): 2 # Write your code here. 3 longestPeakLength = 0 4 i = 1 # the first one(index 0) can not be the peak 5 while i < len(array) - 1: #check peak element 6 isPeak = array[i-1] < array[i] and array[i] > array[i+1] 7 if not isPeak: 8 i += 1 9 continue 10 leftIdx = i - 2 # expand the left side around peak 11 while leftIdx >=0 and array[leftIdx] < array[leftIdx + 1]: 12 leftIdx -= 1 13 rightIdx = i + 2# expand the right side around peak 14 while rightIdx < len(array) and array[rightIdx] < array[rightIdx - 1]: 15 rightIdx += 1 16 17 currentPeakLength = rightIdx - leftIdx - 1 # calculate the length of current peak 18 longestPeakLength = max(longestPeakLength, currentPeakLength) # update the longest length of peak 19 i = rightIdx # update i, inside the rightIdx will be the part of calculated peak, we don't need to recalculate 20 return longestPeakLength 21
Time and Space complexity
Time: O(N)-> outer loop. iterate the array once, inner loop, every element will be checked at most two or three times.(2N + 3N) -> O(N)
Space: O(1)
这篇关于Longest Peak的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-10百万架构师第十三课:源码分析:Spring 源码分析:Spring核心IOC容器及依赖注入原理|JavaGuide
- 2025-01-10便捷好用的电商API工具合集
- 2025-01-09必试!帮 J 人团队解决物流错发漏发的软件神器!
- 2025-01-09不容小觑!助力 J 人物流客服安抚情绪的软件!
- 2025-01-09为什么医疗团队协作离不开智能文档工具?
- 2025-01-09惊叹:J 人团队用啥软件让物流服务快又准?
- 2025-01-09如何利用数据分析工具优化项目资源分配?4种工具推荐
- 2025-01-09多学科协作难?这款文档工具可以帮你省心省力
- 2025-01-09团队中的技术项目经理TPM:工作内容与资源优化策略
- 2025-01-09JIT生产管理法:优化流程,提升竞争力的秘诀