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
.
More practice:If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
思路:1. 取數組的第一個元素當做當前最大值curSum和最終最大值maxSum。然后從list第一個元素開始。如果num是正數,則將curSum+num賦給curSum。然后將curSum賦給maxSum。如果num是負數,則取num和curSum+num之間的大值(因為curSum+num的值有可能小于num的),在將curSum和maxSum之間的大值賦給maxSum。
- 依次從第一個元素遍歷list,然后比較nums[i]和nums[i] + nums[i-1]的大小,到第i個值的時候,這時候nums[i]是當前最大,如果繼續遍歷下去,就是比較nums[i+1]+nums[i]和nums[i+1]的大小,如果nums[i+1]是正值,則毫無疑問nums[i+1]+nums[i]大,如果nums[i+1]小于0,則取nums[i+1]+nums[i]和nums[i+1]的大值,依次循環下去,nums里面就會保留每次循環的大值,最后在其中選取最大值。
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
curSum = maxSum = nums[0]
for num in nums[1:]:
curSum = max(num, curSum + num)
print num, "curSum:", curSum
maxSum = max(curSum, maxSum)
print "maxSum:", maxSum
return maxSum
def maxSubArray2(self, nums):
for i in xrange(1, len(nums)):
nums[i] = max(nums[i], nums[i] + nums[i-1])
print i, " == ", nums
return max(nums)
if __name__ == '__main__':
sol = Solution()
s = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
# print sol.maxSubArray(s)
print sol.maxSubArray2(s)