具有最大和的子数组的大小的Java程序
给定一个数组,找出总和最大的子数组的长度。
例子 :
Input : a[] = {1, -2, 1, 1, -2, 1}
Output : Length of the subarray is 2
Explanation: Subarray with consecutive elements
and maximum sum will be {1, 1}. So length is 2
Input : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 }
Output : Length of the subarray is 5
Explanation: Subarray with consecutive elements
and maximum sum will be {4, -1, -2, 1, 5}.
这个问题主要是最大和连续子数组问题的变体。
这个想法是每当此处结束的总和小于 0 时更新起始索引。
Java
// Java program to print length of the largest
// contiguous array sum
class GFG {
static int maxSubArraySum(int a[], int size)
{
int max_so_far = Integer.MIN_VALUE,
max_ending_here = 0,start = 0,
end = 0, s = 0;
for (int i = 0; i < size; i++)
{
max_ending_here += a[i];
if (max_so_far < max_ending_here)
{
max_so_far = max_ending_here;
start = s;
end = i;
}
if (max_ending_here < 0)
{
max_ending_here = 0;
s = i + 1;
}
}
return (end - start + 1);
}
// Driver code
public static void main(String[] args)
{
int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
int n = a.length;
System.out.println(maxSubArraySum(a, n));
}
}
输出 :
5
有关更多详细信息,请参阅有关具有最大总和的子数组的大小的完整文章!