Leetcode-Maximum Subarray-Python
2017-08-13 18:40
274 查看
Maximum Subarray
最大子串和问题:从一个数组中找出一个子串使其和最大。Description
tips:
子串是指数组中连续的若干个元素,而子序列只要求各元素的顺序与其在数组中一致,而没有连续的要求。
解题思路:
自己没有想出来,直接借鉴了网上的动态规划思路,我觉得下面是一些解决的关键点:
- 对于array[1…n],如果array[i…j]就是满足和最大的子串,那么对于任何k(i<=k<=j),我们有array[i…k]的和大于0。具体证明
- 假设已知0, .., k的最大和sum[k]以后,则0, …, k+1的最大和sum[k+1]分为以下两种情况:
1)若sum[k]>=0,则sum[k+1]=sum[k]+A[k+1]。代码中即curSum = curSum+nums[i]。
2)若sum[k]<0,另起一个SubArray,令sum[k+1]=A[k+1]。代码中即curSum = nums[i]。
def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 curSum = maxSum = nums[0] for i in range(1, len(nums)): curSum = max(nums[i], curSum+nums[i]) maxSum = max(maxSum, curSum) return maxSum
相关文章推荐
- leetcode_[python/C++]_19. Remove Nth Node From End of List(删除链表末第n个节点)
- 【python】【leetcode】【算法题目7—Reverse Integer】
- [LeetCode 415] Add Strings(Python)
- 59. Spiral Matrix II Leetcode Python
- [leetcode: Python]235. Lowest Common Ancestor of a BST
- 9. Palindrome Number Leetcode Python 2016 new Season
- LeetCode--437. Path Sum III(路径和)Python
- Leetcode 75 python
- [Leetcode]@python 79. Word Search
- leetcode-python 第十三周
- Python [Leetcode 342]Power of Four
- python写算法题:leetcode: 13. Roman to Integer
- leetcode 【 Merge k Sorted Lists 】python 实现
- [LeetCode By Python]38. Count and Say
- 【LeetCode with Python】 Copy List with Random Pointer
- [leetcode: Python]290.Word Pattern
- 【LeetCode with Python】 Single Number II
- 【LEETCODE】329-Longest Increasing Path in a Matrix [Python]
- python写算法题:leetcode: 16. 3Sum Closest
- [LeetCode BY Python]169. Majority Element