Monday, February 7, 2011

Finding Maximum Subset Sum

Given an array of integers, find the maximum subset sum. 

For example, if the array is, 4 5 6 -2 3 4 -10 1 2 3, then the maximum sum is 20, and the range is 0 to 5.

If the array is, 1 2 3 -10 4 5 6 -2 3 4, then the maximum sum is 20, and the range is 4 to 9.



#include<stdio.h>
main()
{
int i, n;
int a[100];
int start=-1, end=-1, sum=0;
int maxstart=-1, maxend=-1, maxsum=0;
printf("Enter the count: ");
scanf("%d", &n);
printf("Enter the numbers\n");
for(i=0; i<n; i++) {
scanf("%d", &a[i]);
}
start = 0;
end = 0;
for(i=0; i<n; i++) {
sum += a[i];
end = i;
if(sum < 0) {
start = i+1;
sum = 0;
}
if(sum > maxsum) {
maxstart = start;
maxend = end;
maxsum = sum;
}
}
printf("sum = %d\nstart = %d\nend = %d\n", maxsum, maxstart, maxend);
}

No comments:

Post a Comment