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
.
描述
给出一个整型数组,求连续子串的最大和
分析
假设前 k
个整数中,A[i]
到 A[k]
的子串和最大,为 sum(i,k)
,取下一个元素 A[k+1]
,有以下三种情况:
sum(i,k+1) < 0
,代表会给之后的子串带来负影响,所以使子串从下一个元素开始重新累加sum(i,k+1) > 0
,代表会给之后的子串带来正影响,所以继续累加sum(i,k+1) == 0
,代表并不会影响之后的子串,所以是否累加并不影响,和sum(i,k+1) > 0
一起处理
代码
1 | public class Solution { |