Wednesday, June 29, 2016

#codingexercises 
Write  a method to delete all the nodes from a binary tree that lie on a path whose sum from root to leaf is less than a given value K.  
Void delPathSums(Node root, int K, ref int cur) 
If (Root == null) return; 
Cur+= root.data; 
Int left = cur; 
Int right = cur; 
Root.left = delPathSums(root.left , K, ref int left); 
Root.right = delPathSums(root.right, K, ref int right); 
Cur += max(left, right); 
If (cur <k){ 
Tree_delete(root); 
Root = null; 
Return root; 
}
Merge k sorted arrays

List<int> mergeSorted(List<List<int>> sorted, int k, int m)
{
Var result = new List<int>();
Var cur = new List<int> (); // local index
For(int k =0; k <  m×k ; k++)
{
Var min = getMin(sorted, ref cur);
Result.add(min.first);
Cur[min.second]++;
}
Return result;
}

Tuple<int,int> GetMin(List<List<int>> sorted, ref List<int>cur)
{
var min = new List<int>();
for (int I = 0; I < cur.Count; i++)
{
if (cur[i] < sorted[i].Count)
min.Add(sorted[i][cur[i]]);
else{
min.Add(INT_MAX);
}
}
int val = min.min();
int index = min.index(x = > x == val);
return new Tuple<int, int>(val, index);
}

This could also be solved with a heap
List<int> mergeSortedWithHeap(List<List<int>> sorted, int k)
{
var ret = new List<int>();
var h = new Heap();
for (int i =0; i  < n*k; i++)
{
var root = h.getMin();
ret[i] = root.data;
if (root.localindex < n)
{
root.data = sorted[root.globalindex][root.localindex];
root.localindex += 1;
}
else root.element = INT_MAX;
h.replaceMin(root);
}
return ret;
}

Given a 2d array find the maximum sum rectangle
int FindMaxSum(int[,] nums, int row, int col)
{
int max = 0;
for (int i =0; i < row; i++)
  for (int j = 0; j < col; j++)
  {
     int cur = 0;
     var start = new Tuple<int, int> (i,j);
     // choose end to be one of the remaining points to the right and bottom of start
      for (int x = i; x < row; x++)
        for (int y = j; y < col; y++)
            if (x !==i && y !== j) 
                cur = GetSum(nums, i, j, x,y); 
                 if (cur > max) max = cur;
  }
}
return max;

No comments:

Post a Comment