#coding questions
1) Given a cost matrix cost[,] with positive integers find the minimum cost between a target cell and origin. The permitted moves are right, down and down right.
void GetMinCost(int[, ] cost, int rows, int cols, int x, int y, ref sum )
{
if ( x < 0 || y < 0 || x >= rows || y>= cols) {sum += INT_MAX; return;}
sum += cost[x,y];
if (x == 0 && y == 0) return;
sum += min( GetMinCost(cost, rows, cols, x-1,y-1, ref sum),
GetMinCost(cost, rows, cols, x,y-1, ref sum),
GetMinCost(cost, rows, cols, x-1,y, ref sum);
}
2) Buy or sell 1 stock many times on different days to maximize profit from a daily price list
int GetMaxProfit(List<int> prices)
{
int start = prices[0];
profit = 0;
for (int i = 1; i < prices.Count; i++)
{
if ( prices[i] < prices[i-1])
{
profit += prices[i-1]-start;
start = prices[i];
}
}
if (prices.Count > 0)
{int last = prices[price.Count-1] ;
if (last > start)
profit += last -start;
}
return profit;
}
Reverse a linked list
Node* reverse(node* root)
{
if (root == null) return null;
Node* prev = null;
Node* cur = root;
while(cur)
{
Node* next = cur->next;
cur->next = prev;
prev = cur
cur = next;
}
return prev;
}
1->2->3
3->2->1
Today we are going hiking down the Snoqualmie falls.
1) Given a cost matrix cost[,] with positive integers find the minimum cost between a target cell and origin. The permitted moves are right, down and down right.
void GetMinCost(int[, ] cost, int rows, int cols, int x, int y, ref sum )
{
if ( x < 0 || y < 0 || x >= rows || y>= cols) {sum += INT_MAX; return;}
sum += cost[x,y];
if (x == 0 && y == 0) return;
sum += min( GetMinCost(cost, rows, cols, x-1,y-1, ref sum),
GetMinCost(cost, rows, cols, x,y-1, ref sum),
GetMinCost(cost, rows, cols, x-1,y, ref sum);
}
2) Buy or sell 1 stock many times on different days to maximize profit from a daily price list
int GetMaxProfit(List<int> prices)
{
int start = prices[0];
profit = 0;
for (int i = 1; i < prices.Count; i++)
{
if ( prices[i] < prices[i-1])
{
profit += prices[i-1]-start;
start = prices[i];
}
}
if (prices.Count > 0)
{int last = prices[price.Count-1] ;
if (last > start)
profit += last -start;
}
return profit;
}
Reverse a linked list
Node* reverse(node* root)
{
if (root == null) return null;
Node* prev = null;
Node* cur = root;
while(cur)
{
Node* next = cur->next;
cur->next = prev;
prev = cur
cur = next;
}
return prev;
}
1->2->3
3->2->1
Today we are going hiking down the Snoqualmie falls.
No comments:
Post a Comment