The JustWorks job interview

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com

One of the most popular posts I’ve written is “Embarrassing code I wrote under stress at a job interview“. People get a laugh out of the dumb things I do doing job interviews. Here is another such post.

I did a job interview at JustWorks. They asked me to write the code to solve this problem:

The cost of a stock on each day is given in an array, find the max profit that you can make by buying once and selling once within those days.

For example, if the given array is [100, 180, 260, 590, 40, 310, 535, 10, 5, 3, 2], the maximum profit can earned by buying on day 5 ($40) and selling on day 7 ($535). The max profit in this case is $495.

The first thing I did was pseudo Ruby code:

prices = [100, 180, 260, 590, 40, 310, 535, 10, 5, 3, 2]

biggest_profit = prices.highest – prices.lowest

Then they explained that I’m suppose to treat the array as chronological. That is, I have to have a low price followed by a high price. So simply looking for the lowest and highest price is incorrect.

So then I went off on the wrong tangent, trying to think chronologically. I started to track the lowest_price and the highest_price, thinking that if I knew those 2 things I could find the biggest gap between them. And I thought about using slice() to resize the array as I iterated over it, to eliminate the need to go backwards (for efficiency). Oh, but wait, I don’t need the highest_price, I just need a high price that comes after a low price. And I don’t really want the lowest_price, since the lowest price might be the last element in the array. I need a low price followed by a high price?

I spent 30 minutes writing a bunch of complicated code to try to track the low/high chronologically.

Then the interview ended.

Afterwards I realized how simple this could be: I only needed to track the biggest gap between any number and the numbers that follow it. So, in Javascript-ish code, this would work:

var prices = [100, 180, 260, 590, 40, 310, 535, 10, 5, 3];
var biggest_profit = 0;

for (var i=0; i < prices.length; i++) {
var first_price = prices[i];

for (var j=i+1; j <= prices.length; j++) {
var second_price = prices[j];
var possible_profit = second_price – first_price;

if (possible_profit > biggest_profit) {
biggest_profit = possible_profit;
}
}
}

I never think of these things when I’m in a job interview. It’s really a miracle that I ever get a job.

Also interesting:

Source