Write a C program to find the sum of contiguous subarray within an int array which has the largest sum. A subarray may have a length from 1 to the length of the array. For example, if the array is [1, -3, 2, 9, -2, 10], then the subarray with the largest sum is [2, 9, -2, 10], so your program should print the sum of the subarray which is 19. Hint: Your function should call sumOfSubarray().
ANSWER: Here I am giving you the code and output please like it or comment your problem .
CODE:
#include <stdio.h>
int sumOfSubarray(int a[], int size)
{
int maxSum = 0, maxEndSum = 0;
for (int i = 0; i < size; i++)
{
maxEndSum = maxEndSum + a[i];
if (maxSum < maxEndSum)
maxSum = maxEndSum;
if (maxEndSum < 0)
maxEndSum = 0;
}
return maxSum;
}
int main()
{
int a[] = {1, -3, 2, 9, -2, 10};
int n = sizeof(a)/sizeof(a[0]);
int max_sum = sumOfSubarray(a, n);
printf("Maximum sum :%d",max_sum);
return 0;
}
OUTPUT:
Get Answers For Free
Most questions answered within 1 hours.