Microsoft Interview Question
Software Engineer / DevelopersTeam: Windows Live
Country: United States
Interview Type: In-Person
This is incorrect.. With this you can get a solution such that buyday > sellday which is NOT a valid solution
This is incorrect.. With this you can get a solution such that buyday > sellday which is NOT a valid solution
Nope. You won't get buyday > sellday. The only possibility is that you'll get an answer of 0 if buyday = sellday = 0, which could happen (the "only winning move is not to play" situation). But I consider that to be the preferred answer in that case anyway...
I haven't thought through all the potential corner cases, but this seems correct to me.
Assuming stock is always positive int. buy and sell are -1s if stock is always losing.
void BestDaysToSell(int []days, out int buy, out int sell)
{
int buy = -1;
int sell= -1;
int currBuy = days[0];
int currSell= int.MinValue;
for(int i=1;i<days.Length; i++)
{
if(days[i] < currbuy)
{
currSell=days[i]
currBuy = days[i];
}
else if(days[i] > currSell)
{
currSell = days[i];
if(days[i] - currBuy > sell - buy)
{
buy = currSell;
sell = currBuy;
}
}
}
}
Using a MinStack, that is, a stack with push, pop and min operations having O(1) complexity. This runs in O(n).
public class MaximizeProfit {
public int maximize(Integer[] stockPrice){
int maxProfit=0;
MinStack<Integer> stack = new MinStack<Integer>();
stack.push(stockPrice[0]);
for(int i=1; i<stockPrice.length; i++){
if( (stockPrice[i] - stack.min()) > maxProfit ) {
maxProfit = stockPrice[i] - stack.min();
}
// stack.min() will return the minimum element from 0 to i-1
stack.push(stockPrice[i]);
}
return maxProfit;
}
}
def maximizeProfit(input):
maxDiff = float("-inf")
currentDiff = float("-inf")
bottom = input[0]
max = 0
for index in range(1,len(input)):
currentDiff += input[index] - input[index-1]
if (currentDiff > maxDiff):
maxDiff = currentDiff
max = input[index]
if (bottom > input[index]):
print(currentDiff)
bottom = input[index]
currentDiff = 0
print("buy at :"+str(max - maxDiff)+ " Sell at: "+str(max))
- nim January 17, 2012