topic:
Find the contiguous subarray within a 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. The following:
Finds the largest contiguous subsequence in an array.
For example, given an array [−2,1,−3,4,−1,2,1,−5,4],
wherein the sequential subsequence [4,−1,2,1] has the largest and 6. Algorithm Analysis:
This topic is a dynamic programming problem (DP). The maximum subsequence of the first k elements is known and the Maxsub (which has been recorded), and a temp and sum, if the element k+1 is added, because it is a continuous subsequence, so if the sum of k+1 is less than 0, then for the increase of K + 1 This element to make up the maximum subsequence is not contributing, so you can set the sum to 0. For instance,-1,-2, 4,-5, 7 it is assumed that 7 is the first K+1 element, so it is obvious that the sum =-5 + 4 =-1, then this will only reduce it for 7来, so the correct answer can be obtained directly by placing sum = 0, 0 + 7. Then expand this array,-1,-2, 4,-5, 7, 1 before sum = 1 > 7, which is a contribution to the subsequent one composing the maximum subsequence, so sum = 0 + 7 = 1. Again, as long as the sum is not reduced to a negative number, the middle of less than 0 elements are not related, sum can still continue to accumulate. The code is as follows:
public class Solution
{public
int maxsubarray (int[] nums)
{
int sum = nums[0], maxsum = nums[0];
for (int i = 1; i < nums.length i++)
{
if (sum < 0) sum = 0; First judge whether the sum can be used this time (less than 0 is discarded)
sum + + + nums[i];
Maxsum = Math.max (maxsum, sum);
}
Return maxsum
}
}