【leetcode-python-14-动态规划】面试题 16.17. 连续数列

博客介绍了使用Python解决LeetCode面试题16.17,即寻找连续数列的动态规划方法。博主分享了原始版本和参考优化版本的代码,两者效率相同,均为70.23%通过率,并引用了题解区腐烂的橘子�的思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【leetcode-python-14】面试题 16.17. 连续数列

leetcode 面试题 16.17. 连续数列

渣渣原始版(70.23%)

以下两者在<0算max不同。均为70.23%。

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for i in nums:
            if i >= 0:
                break
        else:
            return max(nums)
        
        max1 = 0
        save = 0
              
        for num in nums:
            if num + max1 > 0:
                max1 += num
            else:
                max1 = 0
                
            if max1 > save:
                save = max1
        
        return save
class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        max1 = nums[0]
        for i in nums:
            if i >= 0:
                break
            elif max1 < i:
                max1 = i
        else:
            return max1
         
        max1 = 0
        save = 0

        for num in nums:
            if num + max1 > 0:
                max1 += num
            else:
                max1 = 0
                
            if max1 > save:
                save = max1
 
        return save

参考大佬版(70.23%)

老老实实的动态规划。
注:参考题解区腐烂的橘子🍊思路。

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        max1 = float('-inf')
        save = float('-inf')
           
        for num in nums:
            max1 = max(num, num+max1)
            save = max(save, max1)              
           
        return save

新手入坑,多多包涵~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值