GREATEST CONTIGUOUS SUM
namespace ArrayProblem
{
//Write a function that takes an array as an input and returns starting and ending indexes
//within the array such that if we add elements from the starting and ending index
//we would get maximum possible sum of any contiguous set
//of elements within that array.
public static void GreatestContiguousSum(int[] Arr, out int StartIndex, out int EndIndex)
{
int sum = 0;
int finalsum = int.MinValue;
int tempStartIndex = 0;
StartIndex = 0;
EndIndex = 0;
for (int i = 0; i < Arr.Length; i++)
{
if (sum <= 0)
{
tempStartIndex = i;
sum = 0;
}
sum = sum + Arr[i];
if (sum > finalsum)
{
StartIndex = tempStartIndex;
EndIndex = i;
finalsum = sum;
}
}
}
static void Main(string[] args)
{
int[] Arr2 = { -9, -5, -4, -8, 4, -1, -2, 14 };
int StartIndex;
int EndIndex;
GreatestContiguousSum(Arr, out StartIndex, out EndIndex);
Console.Write(StartIndex + " " + EndIndex);
}
}
}
No comments:
Post a Comment