Leetcode#53. Maximum Subarray(连续子序列的最大和)

本文介绍了一种寻找数组中具有最大和的连续子数组的方法。提供了两种解决方案:一种是时间复杂度为O(n²)的暴力解法,另一种是优化后的O(n)解法,并附带了C++和Python代码实现。

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

题目

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

题意

从数组中求出连续数的和的最大值。

思路

1. 暴力解法(时间复杂度为O(n2) 超时了)

C++语言

class Solution {
public:
    int maxSubArray(vector<int>& nums) 
    {
        int max=-pow(2,31),temp=0;
        for(int i=0; i<nums.size(); i++)
        { 
            temp = 0;
            for(int j=i; j<nums.size(); j++)
            {
                temp+=nums[j];
                if(max<temp)
                    max = temp;
            }
        }
        return max;
    }
};

2. 优化解法 (时间复杂度为0(n))
设temp为数组遍历的累加值,当前累加值大于大于max_sum时就将temp的值记录给max_sum,一旦当前的累加值小于0时,就将temp重置为0,接着累加。

C++语言

class Solution {
public:
    int maxSubArray(vector<int>& nums) 
    {
        int max=-pow(2,31),temp=0;
        for(int i=0; i<nums.size(); i++)
        { 
           temp += nums[i];
           if(temp > max)
               max = temp;
           if(temp< 0)
               temp = 0;
        }
        return max;
    }
};

Python语言

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        max = -(1<<31)
        temp = 0
        for num in nums:
            temp = temp + num
            if temp > max:
                max = temp
            if temp < 0:
                temp = 0
        return max
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值