i was trying to solve problem related to prefix sum. In which array is given
var nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
and we have to find Sum of each elements in range a, b inclusive
function is giving System.IndexOutOfRangeException
I Tried to solve this ways.
int[] pre;
NumArray(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
Console.WriteLine(SumRanges(0,2));
Console.WriteLine(SumRange(0,2));
void NumArray(int[] nums)
{
pre = new int[nums.Length];
pre[0] = nums[0];
for (var i = 1; i < nums.Length; i++)
{
pre[i] += pre[i - 1] + nums[i];
}
}
int SumRange(int left, int right)
{
return pre[right] - left >= 1 ? pre[left - 1] : 0;
}
int SumRanges(int left, int right)
{
int l = left >= 1 ? pre[left - 1] : 0;
return pre[right] - l;
}
My Question is Why below function is giving System.IndexOutOfRangeException
int SumRange(int left, int right)
{
return pre[right] - left >= 1 ? pre[left - 1] : 0;
}
but below equation won't give System.IndexOutOfRangeException
int SumRanges(int left, int right)
{
int l = left >= 1 ? pre[left - 1] : 0;
return pre[right] - l;
}
i just only stored in variable, i am not getting why it is?
Please help me.