-
Maximum Subarray
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.
-
题目大意:求最长子序列和。给定一个至少包含一个数字的数组,查找最长子序列和。
例如:给定的是数组[−2, 1, −3, 4, −1, 2, 1, −5, 4],最大连续子序列是[4, -4, 2, 1],最长子序列和是6。
更多练习:如果已经找到O(n)解决方案,尝试使用分治法解决方案。
-
思路:maxSum 必然是以A[i](取值范围为A[0] ~ A[n-1])结尾的某段构成的,也就是说maxSum的candidate必然是以A[i]结果的。如果遍历每个candidate,然后进行比较,那么就能找到最大的maxSum了。
假设把A[i]之前的连续段叫做sum。可以很容易想到:
(1)如果sum>=0,就可以和A[i]拼接在一起构成新的sum。因为不管nums[i]多大,加上一个正数总会更大,这样形成一个新的candidate。
最长子序列和
最新推荐文章于 2020-06-23 14:28:47 发布