【Golang】LeetCode 53. 最大子数组和

53. 最大子数组和

题目描述

思路

我们只需设置两个变量来分别记录答案和当前子数组可能的最大和即可解决问题。

具体来说,我们设置ans, curr = nums[0], nums[0],随后开始对nums进行遍历。

由于数组当中可能会出现负数,我们使用curr来对数组和的中间状态进行记录,当curr + nums[i] < nums[i]时,说明当前的子数组和已经比当前数值更小了,此时我们重新开始统计子数组和,令curr = nums[i]

每一次遍历时,令ans = max(ans, curr),最终得到的即是答案。

基于以上思路,我们写代码来解决问题。

Golang 题解

go 复制代码
func maxSubArray(nums []int) int {
    ans, curr, n := nums[0], nums[0], len(nums)
    for i := 1; i < n; i ++ {
        if curr + nums[i] < nums[i] {
            curr = nums[i]
        } else {
            curr += nums[i]
        }
        ans = max(ans, curr)
    }
    return ans
}

Python 题解

python 复制代码
class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        ans, curr, n = nums[0], nums[0], len(nums)
        for i in range(1, n):
            if curr + nums[i] < nums[i]:
                curr = nums[i]
            else:
                curr += nums[i]
            ans = max(ans, curr)
        return ans
相关推荐
xlp666hub5 小时前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
xlp666hub9 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
xlp666hub1 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
琢磨先生David11 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝11 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll11 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐11 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶11 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
im_AMBER11 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了11 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表