Maximum Number in Mountain Sequence – Python 3 (Week 17 – 14)

class Solution:
    """
    @param nums: a mountain sequence which increase firstly and then decrease
    @return: then mountain top
    """
    def mountainSequence(self, nums):
        # write your code here
        if not nums:
            return None
        
        length = len(nums)
        
        if length == 1:
            return nums[0]
            
        start = 0
        end = length - 1
        
        while start + 1 < end:
            mid = start + (end - start) // 2
            if nums[mid - 1] < nums[mid]:
                start = mid
            else:
                end = mid
            
        if nums[start] > nums[end]:
            return nums[start]
        else:
            return nums[end]

Leave a comment

Design a site like this with WordPress.com
Get started