问题描述:
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.
思路:
动态规划问题,从头开始遍历数组,每次都考虑以 当前索引为结束位置 的所有数组求和的最大值,依次类推,从而依次得到以 每一个索引为结束位置的 相应所有数组求和最大值,进而形成一个列表,取该列表最大值即可
class Solution: def maxSubArray(self, nums: List[int]) -> int: dp = [0 for i in (range(len(nums)+1))] dp[0] = float("-inf") for i in range(1,len(nums)+1): dp[i] = max(dp[i-1]+nums[i-1],nums[i-1]) return max(dp)