前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 53. 最大子序和

LeetCode 53. 最大子序和

作者头像
freesan44
发布2020-03-20 10:04:26
2340
发布2020-03-20 10:04:26
举报
文章被收录于专栏:freesan44

题目

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

代码语言:javascript
复制
示例:

输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。

进阶:

如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。

解题思路

贪心算法,并记录最大值

代码语言:javascript
复制
class Solution:
    def maxSubArray(self, nums: [int]) -> int:
        #穷举法
        # maxNum = max(nums) #记录最大值
        # tempList = nums
        # # print(tempList)
        # for i in range(len(nums)):
        #     # print("tempList: "+str(tempList[1:]))
        #     # print("nums: "+ str(nums[:-i-1]))
        #     tempList = [a+b for a,b in zip(tempList[1:],nums[:-i-1])]
        #     # print(tempList)
        #     if len(tempList)>0 and maxNum < max(tempList):maxNum = max(tempList)
        #     # print(maxNum)
        # return maxNum
        #贪心算法
        maxLength = len(nums)
        tempList = [nums[0]] #记录临时数组
        maxNum = nums[0]
        for i in range(1, maxLength):
            tempList.append(nums[i])
            if sum(tempList) > nums[i]:#加了当前元素后临时最大量上升就继续添加,否则就重置
                maxNum = max(maxNum, sum(tempList))
            else:
                tempList = [nums[i]]
                maxNum = max(maxNum, nums[i])
        return maxNum
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 解题思路
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档