[leetcode] 53. Maximum Subarray @ python

本文深入探讨了LeetCode上经典题目“最大子数组和”的两种高效解法:Kadane’s算法和动态规划。通过实例讲解,展示了如何在O(n)时间复杂度内找到连续子数组的最大和,适合算法初学者和进阶者学习。

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

原题

https://leetcode.com/problems/maximum-subarray/
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

解法1

使用Kadane’s 算法, 遍历数组, 计算在i点时的最大和 max_end_here, 并更新max_so_far, https://en.wikipedia.org/wiki/Maximum_subarray_problem#Kadane’s_algorithm
Time: O(n)
Space: O(1)

代码

class Solution:
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        max_end_here = max_so_far = nums[0]
        for i in range(1, len(nums)):
            max_end_here = max(nums[i], nums[i] + max_end_here)
            max_so_far = max(max_so_far, max_end_here)
        return max_so_far

解法2

动态规划, 初始化dp数组, dp[i]表示在i点最大的子数组. 状态转移方程:

dp[i] = dp[i-1] + nums[i] if dp[i-1] > 0 else nums[i]

然后我们求dp中最大的值即可.

代码

class Solution:
    def maxSubArray(self, nums: 'List[int]') -> 'int':
        dp = nums[:]
        for i in range(1, len(nums)):
            if dp[i-1] > 0:
                dp[i] = dp[i-1] + nums[i]
            else:
                dp[i] = nums[i]
                
        return max(dp)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值