Largest Sum Contiguous Subarray in C (Also works for all negative elements)
Largest Sum Contiguous Subarray
This code also works on all negative number.
#include<stdio.h>void maxSumSubArray(int *arr,int arr_size,int &left_index,int &right_index, int &sum)
{
int cur_sum,temp,i;
sum=cur_sum=arr[0];
left_index=right_index=0;
for(i=1;i<arr_size;i++)
{
temp=cur_sum+arr[i];
if(arr[i]>=temp && arr[i]>sum)
{
left_index=right_index=i;
sum=cur_sum=arr[i];
continue;
}
cur_sum=temp;
if(temp>sum)
{
right_index=i;
sum=temp;
}
}
}
int main()
{
int arr[]={1,-3,6,-5,9,-6,4};
int left_index,right_index,sum;
maxSumSubArray(arr,sizeof(arr)/sizeof(int),left_index,right_index,sum);
printf("Left_Index: %d \nRight_Index: %d\nSum: %d",left_index,right_index,sum);
return 0;
}
Output:
Left_Index: 2Right_Index: 4
Sum: 10
Input Array: (For all negative input)
arr[]={-3,-2,-1,-4,-5-7-9};Output:
Left_Index: 2Right_Index: 2
Sum: -1
Comments
Post a Comment