Hello.
i was trying to solve this problem:
You’re given an array containing both positive and negative integers and required to find the subarray with the largest sum (O(N)). Write a routine in C for the above.
i was able to find the largest sum. However,i had little trouble finding the subarray.
Can anyone please help?
Thanks.
#include <stdio.h>
int main(void)
{
int arr[] = {1, 0, -1, -1, 2, 3, 1, -2};
int sum = 0, max = 0;
for (int i = 0; i < 8; i++) {
if (arr[i] < 0) {
sum = 0;
continue;
} else {
sum += arr[i];
if (sum > max) {
max = sum;
}
}
}
printf("\nAnwser is%d", max);
getchar();
return 0;
}