Maximum Subarray
Given an array of integers, find a contiguous subarray which has the largest sum.
Example
Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.
Solution
(1) Greedy
sum is the running number which keep running for the sum
the max should be currnt sum running - min sum running.
(2) Prefix
(3) DP
全局局部, 划分型动态规划
class Solution:
"""
@param nums: A list of integers
@return: An integer denote the sum of maximum subarray
"""
def maxSubArray(self, nums):
# write your code here
maxSum = sys.maxsize * -1
sum = 0
for x in nums:
sum += x
maxSum = max(maxSum, sum)
sum = max(sum, 0)
return maxSumDP
Last updated
Was this helpful?