典型動態(tài)規(guī)劃問題
Find the contiguous subarray within an array (containing at least
one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4]
,the contiguous subarray [4,-1,2,1]
has the largest sum = 6
.
思路非常簡單但荤,維持兩個變量,一個全局最大戴已,一個局部最大
class Solution(object):
"""
:type nums: List[int]
:rtype: int
"""
def maxSubArray(self, nums):
Max = nums[0]
F = 0
for x in nums:
if F > 0:
F += x
else:
F = x
if F > Max:
Max = F
return Max