LeetCode 53. Maximum Subarray

简介: 给定整数数组nums,找到具有最大总和的子数组(数组要求连续)并且返回数组的和,给定的数组包含至少一个数字。

Description



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.


描述



给定整数数组nums,找到具有最大总和的子数组(数组要求连续)并且返回数组的和,给定的数组包含至少一个数字。


思路



  • 我们用res来表示最终的和,用temp来表示临时的和
  • 初始时res = nums[0],temp = 0
  • 遇到一个值,我们就把它加到temp上面,如果temp大于res,把temp赋值给res
  • 如果temp小于res但是大于0,继续加和
  • 如果temp小于零,我把temp置为零,因为此时temp已经小于零了,如果保留temp当前的值再往里面加值,整个的和一定会变得更小[因为temp当前是负数],
  • 也就是说当temp是负数时,temp的贡献一定是负,无论后面加什么值,一定会使得当前的子数组和更小


class Solution:
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # 初始化为nums[0]
        res = nums[0]
        temp = 0
        for item in nums:
            # 往temp加和
            temp += item
            # 如果比res大,更新res
            if temp > res:
                res = temp
            # 如果小于0,则重置为0
            if temp < 0:
                temp = 0
        return res


源代码文件在这里

目录
相关文章
|
5月前
Leetcode 53.Maximum Subarray
题意简单,给出一个数组,求出其中最大的子数组和。 这种简单题目背后蕴藏着很巧妙的解题方法。其实只需要遍历一次数组就可以求得解。 思路是这样的,你想想看,如果一段子数组的和是负数, 那么这一段子数组不可能是最大和数组的一部分,丢掉重新从下一个位置开始选。
27 0
LeetCode 104. 二叉树的最大深度 Maximum Depth of Binary Tree
LeetCode 104. 二叉树的最大深度 Maximum Depth of Binary Tree
|
算法
LeetCode 414. Third Maximum Number
给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。
66 0
LeetCode 414. Third Maximum Number
LeetCode 318. Maximum Product of Word Lengths
给定一个字符串数组 words,找到 length(word[i]) * length(word[j]) 的最大值,并且这两个单词不含有公共字母。你可以认为每个单词只包含小写字母。如果不存在这样的两个单词,返回 0。
52 0
LeetCode 318. Maximum Product of Word Lengths
LeetCode 209. Minimum Size Subarray Sum
给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组。如果不存在符合条件的连续子数组,返回 0。
86 0
LeetCode 209. Minimum Size Subarray Sum
LeetCode 164. Maximum Gap
给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。 如果数组元素个数小于 2,则返回 0。
54 0
LeetCode 164. Maximum Gap
LeetCode 152. Maximum Product Subarray
给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
31 0
LeetCode 152. Maximum Product Subarray
|
Python
[Leetcode][python]Maximum Subarray/最大子序和
题目大意 由 N 个整数元素组成的一维数组 (A[0], A[1],…,A[n-1], A[n]),这个数组有很多连续子数组,那么其中数组之和的最大值是什么呢? 子数组必须是连续的。 不需要返回子数组的具体位置。 数组中包含:正整数,零,负整数。
80 0
|
30天前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
1月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记