Nagendra
BAN USERI feel this should be done in o(n)
static int GetMinAbsoluteDiff(int[] a, int[] b)
{
int minDif = int.MaxValue;
int i = 0;
minDif = Math.Min(minDif, Math.Abs(a[i] - b[i]));
minDif = Math.Min(minDif, Math.Abs(a[i] - b[i + 1]));
for (i = 1; i < a.Length-1; i++)
{
minDif = Math.Min(minDif, Math.Abs(a[i] - b[i-1]));
minDif = Math.Min(minDif, Math.Abs(a[i] - b[i]));
minDif = Math.Min(minDif, Math.Abs(a[i] - b[i+1]));
}
minDif = Math.Min(minDif, Math.Abs(a[i] - b[i - 1]));
minDif = Math.Min(minDif, Math.Abs(a[i] - b[i]));
return minDif;
}
Correct me if there are any complexities involved in it.
- Nagendra July 24, 2013static void GetHeight(int [] a)
{
int height=0;
if ( a != null && a.Length > 0)
{
int[] level = new int[a.Length];
for (int i = 0; i < a.Length; i++)
{
int parentNode = a[i];
if (parentNode == -1)
{
level[i] = 1;
}
else
{
if (level[parentNode] == 0)
{
level[parentNode] = 1;
}
level[i] = 1 + level[parentNode];
}
height = Math.Max(height, level[i]);
}
}
Console.WriteLine("Height of tree is : {0}", height);
}
I think the critical point here is finding when to stop the loop. If we are going in only one direction, we cannot be sure if the loop again started or it is going on. I thought the solution would be
- Nagendra November 11, 20151. Start from a random car
2. Go left side 1 step turn off light and come back
3. Go right side 1 step and turn on the light and come back
4. Go left side 2 steps and turn off the light and come back
while going each side keeping in mind the count of the steps we turned on/off previous step
5 Do this until the previous on/off count mismatches one side.
6. Once mismatched come back to original position and start switch on/off the light from original position and counting
7. iterate through untill it reaches to the first point as now we are sure one side lights are on and other side off. So if we start counting from on side, once we cross off side, it is the end and vice versa.