题目描述:
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
题目分析:
该题属于Array类别,通过贪心可以实现O(n)级别的解决思路,通过分治法可以实现O(nlogn)的解决思路。
贪心法O(n)解决思路:
对于序列[A1,A2,...,AN]的遍历中,我们要求序列AI+...+AJ的和最大。
贪心算法在该问题的应用体现在我们在对序列遍历(i)求和的过程中,同时比较序列A0,...Ai的和与Ai的大小关系,两者的max值作为遍历至i时刻的当前序列最大sum.
并将当前序列最大sum与实际最大值比较,当序列遍历完毕,我们则求得整个序列的最大子集和。
Runtime: 72 ms, faster than 91.17% of Python3 online submissions for Maximum Subarray.
Memory Usage: 14.6 MB, less than 5.02% of Python3 online submissions for Maximum Subarray.
length = len(nums)
summax