算法萌新如何学好动态规划(1) https://mp.weixin.qq.com/s/rhyUb7d8IL8UW1IosoE34g
输入一个整型数组,数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
要求时间复杂度为O(n)。
示例1:
输入: nums = [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
提示:
1 <= arr.length <= 10^5
-100 <= arr[i] <= 100
剑指 Offer 42. 连续子数组的最大和 - 力扣(LeetCode) https://leetcode-cn.com/problems/lian-xu-zi-shu-zu-de-zui-da-he-lcof/
53. 最大子序和 - 力扣(LeetCode) https://leetcode-cn.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.
class Solution:
def maxSubArray(self, nums: list) -> int:
len_, option = len(nums), nums[0]
max_ = option
for i in range(len_):
# e.g. 100,-1,-1,-1,300 不应考虑当前项的正负,考虑最终结果值;
# [-2,1,-3,4,-1,2,1,-5,4]
if i == 0:
continue
j = nums[i]
if option >= 0:
option += j
else:
if j > option:
option = j
max_ = max_ if max_ >= option else option
return max_
爬楼梯 - 爬楼梯 - 力扣(LeetCode) https://leetcode-cn.com/problems/climbing-stairs/solution/pa-lou-ti-by-leetcode-solution/