DP之最大連續子序列

最大連續子序列

def maxSubArray(self, nums):

	# 判斷特殊情況
    if len(nums) == 1:
        return nums[0]
        
    # 先初始化
    max_ret = nums[0]
    cur_max = last_max = nums[0]
    
    for i in range(1, len(nums)):
    
    	# 之前的最大連續子序列 和 當前的值 進行比較!!
        if last_max + nums[i] < nums[i]:
            cur_max = nums[i]
        else:
            cur_max = last_max + nums[i]
            
        # 保存最大值        
        if cur_max > max_ret:
            max_ret = cur_max
            
        # 保存當前爲止的最大值
        last_max = cur_max
        
    return max_ret
            
            
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章